Python standard library: Detailed description of the use of the built-in function hasattr () getattr () setattr (), hasattrgetattr
Hasattr (object, name)
This function is used to determine whether the object property (name) exists. If the property (name indicates) exists, True is returned; otherwise, False is returned. The parameter object is an object, and the parameter name is a string representation of an attribute.
1 # coding: UTF8 2 3 class Foo (): 4 def _ init _ (self): 5 self. x = 123 6 def test (x): 7 self. x = x 8 9 foo = Foo () 10 print (hasattr (foo, 'x') # determine whether an object has x attributes 11 print (hasattr (foo, 'y ')) 12 print (hasattr (foo, 'test '))
Output result:
1 True2 False3 True
Getattr (object, name [, default])
Obtain the attributes or methods of the object. If the attributes or methods are printed out, the default value is printed out. The default value is optional. Note that if the method of the returned object is the memory address of the method, you can add a pair of parentheses to the end if you need to run this method.
1 # coding: UTF8 2 3 class Foo (): 4 name = 'Tom '5 def run (self): 6 return 'Hello world' 7 8 f = Foo () 9 print getattr (f, 'name') # obtain the name attribute and print it if it exists. 10 print getattr (f, 'run') # obtain the run method and print out the memory address of the method if it exists. 11 print getattr (f, 'run') () # obtain the run method. You can run this method using parentheses. 12 # print getattr (f, 'age') # obtain an attribute that does not exist. 13 print getattr (f, "age", "18") # If the property does not exist, a default value is returned.
Output result:
1 Tom2 <bound method Foo.run of <__main__.Foo instance at 0x0000000002658B08>>3 hello world4 18
Setattr (object, name, values)
Assign a value to the property of an object. If the property does not exist, create and assign a value first.
1 # coding: UTF8 2 3 class Foo (): 4 name = 'Tom '5 def run (self): 6 return 'Hello world' 7 8 f = Foo () 9 10 print hasattr (f, 'age') # judge whether the attribute exists 11 setattr (f, "age", "18") # If the attribute does not exist, a default value is returned. 12 print hasattr (f, 'age') # determine whether an attribute exists
1 False2 True
View Code