Wednesday, September 6, 2023
Friday, June 5, 2020
getattrib, Setattrib, hasattrib and delattrib in python
# `getattr(object, name[, default])` Function in Python
The `getattr(object, name[, default])` function returns the value of a named attribute of an object, where `name` must be a string. If the object has an attribute with the specified `name`, then the value of that attribute is returned. On the other hand, if the object does not have an attribute with `name`, then the value of `default` is returned, or `AttributeError` is raised if `default` is not provided.
```python
>>> t = ('This', 'is', 'a', 'tuple')
>>> t.index('is')
1
>>> getattr(t, 'index')
<built-in method index of tuple object at 0x10c15e680>
>>> getattr(t, 'index')('is')
1
```
when the attribute is not defined,
# hasattr #uses pythonic "Look Before You Leap" (LBYL) code style
Using try-except way # "Easier to Ask for Forgiveness than Permission" (EAFP) code style
**********
#setattrib --Assigns a value to the object’s attribute given its name.
EX: setattr(x, ‘foobar’, 123) is equivalent to x.foobar = 123
Example 1
```python
>>> getattr(t, 'len') Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'tuple' object has no attribute 'len' >>> getattr(t, 'len', t.count) <built-in method count of tuple object at 0x10c15e680>
```
Besides "normal" objects like tuples, lists, and class instances,
getattralso accepts modules as arguments. Since modules are also objects in Python, the attributes of modules can be retrieved just like any attribute in an object.>>> import uuid >>> getattr(uuid, 'UUID') <class 'uuid.UUID'> >>> type(getattr(uuid, 'UUID')) <type 'type'> >>> isinstance(getattr(uuid, 'UUID'), type) True >>> callable(getattr(uuid, 'UUID')) True >>> getattr(uuid, 'UUID')('12345678123456781234567812345678') UUID('12345678-1234-5678-1234-567812345678')
*****# check for existence of an attribute
# hasattr #uses pythonic "Look Before You Leap" (LBYL) code style
>>> hasattr('abc', 'upper')
True
>>> hasattr('abc', 'lower')
True
>>> hasattr('abc', 'convert')
False
Using try-except way # "Easier to Ask for Forgiveness than Permission" (EAFP) code style
>>> try:
... 'abc'.upper()
... except AttributeError:
... print("abc does not have attribute 'upper'")
...
'ABC'
>>> try:
... 'abc'.convert()
... except AttributeError:
... print("abc does not have attribute 'convert'")
...
abc does not have attribute 'convert'
**********
hasattr vs __dict__
>>> class A(object): ... foo = 1 ... >>> class B(A): ... pass ... >>> b = B() >>> hasattr(b, 'foo') True >>> 'foo' in b.__dict__ False
#setattrib --Assigns a value to the object’s attribute given its name.
EX: setattr(x, ‘foobar’, 123) is equivalent to x.foobar = 123
Example 1
>>> class Foo: ... def __init__(self, x): ... self.x = x ... >>> f = Foo(10) >>> f.x 10 >>> setattr(f, 'x', 20) >>> f.x 20 >>> setattr(f, 'y', 10) >>> f.y 10 >>> f.y = 100 >>> f.y 100you can dynamically add a function as a method to a class
>>> def b(self): print 'bar'
class Foo:
pass
f = Foo() print dir(f) #[‘__doc__’, ‘__module__’] setattr(Foo, ‘bar’, b) print dir(f) #[‘__doc__’, ‘__module__’, ‘bar’] f.bar() #bar
you can setattr() on an instance of a class that
inherits from "object", but you can't on an instance of "object"
itself
it should not simply execute self.name = value — this would
cause a recursive call to itself. Instead, it should insert
the value in the dictionary of instance attributes,
e.g., self.__dict__[name] = value.
For new-style classes, rather than accessing the instance dictionary,
it should call the base class method with the same name,
for example, object.__setattr__(self, name, value).
****for blog****
The __slots__ declaration takes a sequence of instance variables and
reserves just enough space in each instance to hold a value for each
variable. Space is saved because __dict__ is not created for each instance.
When there is '__slots__', there won't be '__dict__' and '__weakref__'
delattr will delete the attribute
inherits from "object", but you can't on an instance of "object"
itself
>>> o = object() >>> setattr(o, "x", 1000) Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'object' object has no attribute 'x'If __setattr__() wants to assign to an instance attribute,
>>> class Object(object):pass ... >>> o = Object() >>> setattr(o, "x", 1000) >>> o.x 1000
it should not simply execute self.name = value — this would
cause a recursive call to itself. Instead, it should insert
the value in the dictionary of instance attributes,
e.g., self.__dict__[name] = value.
For new-style classes, rather than accessing the instance dictionary,
it should call the base class method with the same name,
for example, object.__setattr__(self, name, value).
****for blog****
The __slots__ declaration takes a sequence of instance variables and
reserves just enough space in each instance to hold a value for each
variable. Space is saved because __dict__ is not created for each instance.
When there is '__slots__', there won't be '__dict__' and '__weakref__'
delattr will delete the attribute
Example:
class Box: pass
box = Box()
# Create a width attribute. setattr(box, "width", 15)
# The attribute exists. if hasattr(box, "width"): print(True)
# Delete the width attribute. delattr(box, "width")
# Width no longer exists. if not hasattr(box, "width"): print(False)
Python tips
python tips:
*******
WAP for print a character its position times in a word.
Output:
******
WAP for print a character its ASCII values times in a word.
In [1]: os.listdir(os.getcwd())==os.listdir(os.curdir)
Out[1]: True
In [2]: os.listdir(os.getcwd())==os.listdir('.')
Out[2]: True
*******
WAP for print a character its position times in a word.
word=raw_input("Enter the word:")
for i in word:
print i*word.index(i)
Output:
******
WAP for print a character its ASCII values times in a word.
word=raw_input("Enter the word:")
for i in word:
print i*ord(i)
#alternatively # print [i*ord(i) for i in word]
Sunday, December 17, 2017
Initiating static local HTTP Server using different scripting languages
Initiating HTTP Server using different scripting languages
Python
python 2.x - python -m SimpleHTTPServer 8000
python 3.x - python -m http.server 8000
http-server (Node.js)
npm install -g http-server # install dependency
http-server -p 8000
node-static (Node.js)
npm install -g node-static # install dependency
static -p 8000
Ruby
ruby -rwebrick -e’WEBrick::HTTPServer.new(:Port => 3000, :DocumentRoot => Dir.pwd).start’
Ruby 1.9.2+
- ruby -run -ehttpd . -p3000
adsf (Ruby)
- gem install adsf # install dependency
- adsf -p 8000
Perl
----
cpan HTTP::Server::Brick # install dependency
- $ perl -MHTTP::Server::Brick -e ‘$s=HTTP::Server::Brick->new(port=>8000); $s->mount(“/”=>{path=>”.”}); $s->start’
Plack (Perl)
- cpan Plack # install dependency
- plackup -MPlack::App::Directory -e ‘Plack::App::Directory->new(root=>”.”);’ -p 8000
PHP (>= 5.4)
------------
php -S 127.0.0.1:8000
busybox httpd
-------------
busybox httpd -f -p 8000
webfs
-----
webfsd -F -p 8000
IIS Express
-----------
C:\> “C:\Program Files (x86)\IIS Express\iisexpress.exe” /path:C:\MyWeb /port:8000
AWS CLI installation procedure in centos/ RHEL
1) Make sure you have the epel repository installed
sudo yum install -y epel-release
2) Install needed packages
sudo yum install -y python2-pip
3) Install awscli
sudo yum install -y awscli
4) Configure awscli
aws configure --profile <profile_name>
4) Configure awscli.
If you do not add --profile <profile_name>, it will use the default profile.
aws configure --profile <profile_name>
Using the --profile allows you to create profiles for other accounts using different keys.
You can also create profiles for different regions.
sudo yum install -y epel-release
2) Install needed packages
sudo yum install -y python2-pip
3) Install awscli
sudo yum install -y awscli
4) Configure awscli
aws configure --profile <profile_name>
4) Configure awscli.
If you do not add --profile <profile_name>, it will use the default profile.
aws configure --profile <profile_name>
Using the --profile allows you to create profiles for other accounts using different keys.
You can also create profiles for different regions.
Thursday, October 20, 2016
Saturday, August 27, 2016
Subscribe to:
Comments (Atom)
-
Why I'm the Best Fit for This Role Thank you for the briefing. Now, I can understand more about th...
-
Are you a beginner for ns2 network simulator? Are you afraid of Tcl/oTcl script generation? Then there is a tcl script generator, ...
-
Online Interpreters are useful in many cases. Here are few popular-yet-useful online interpreters for programming, especially for python p...