python built-in function--hasattr&setattr&getattr&delattr
Hasattr & SetAttr & GetAttr & Delattrhasattr (object,name): Used to determine whether or not a name exists in an object. SetAttr (object, name, value): This function assigns a value to an attribute in an object that, if it does not exist, creates a new property in the object Delattr (object, name): Deletes the property of the specified object, Can be used with hasattr getattr (object, name[, default]), object is the name of the objects, Naem is the object property (must be a string), the default is the Name property does not exist when the return content (can be a string, can also be a partial instruction), if the property exists in the object, the function returns OBJECT.NAME, otherwise returns the contents of the default, and if default is omitted, returns ATTRIBUTEERROR. In [4]: Class Test (Object): ...: name = "John" ...: def greet (self): ...: print "Hello,my name is%s "% Name ...:" [5]: a = Test () in [6]: Hasattr (A, ' name ') out[6]: Truein [7]: Hasattr (A, ' greet ') out[7]: Truein [8]: SetAttr (A, ' name ', ' Mark ') In [9]: Print A.namemarkin [ten]: GetAttr (A, ' name ', ' No Exit ') out[10]: ' Mark ' in [All]: GetAttr (A, ' greet ', ' no Exit ') out[11]: <bound method Test.greet of <__main__.test object at 0x0000000003ab8470>>in [b]: GetAttr (A, ' age ', ' no Exit ') OUT[12]: ' No exit ' in [+]: SetAttr (A, ' name ', ' Jane ') in [+]: a.nameout[14]: ' Jane ' in []: SetAttr (A, ' age ', +) in [+]: A.AGEOUT[16]: 20In [+]: GetAttr (A, ' nationality ', setattr (A, ' nationality ', ' englend ')) out[17]: ' Englend ' in [18]: A.NATIONALITYOUT[18]: ' Englend ' in [+]: If Hasattr (A, ' age '): ....: Delattr (A, ' age ') ....: in []: A.age----------- ----------------------------------------------------------------Attributeerror Traceback (most Recent call last) <ipython-input-20-d50340e1fbb7> in <module> ()----> 1 a.ageattributeerror: ' Test ' object has no attribute ' age ' in [+]: b = Test () in [22]: B.nationality---------------------------------------------------------------------------Attributeerror Traceback (most recent) <ipython-input-22-fd8c7f39aa50> in <module> ()----> 1 b.nationality Attributeerror: ' Test ' object has no attribute ' nationality '
The above is the python built-in function--hasattr&setattr&getattr&delattr content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!