[Python] hasattr (), GetAttr (), SetAttr () three relations and application

Source: Internet
Author: User

Hasattr (object, name)

Determines if an object (object) has a Name property or method that returns a Boolean value that has the Name property return True, otherwise false

In [1]: Class Test (object):   ...:     name = ' hkey '   ...:     def hello (self):   ...:         print (' Hello ', Self.name)   : [2]: T = Test () in [3]: Print (hasattr (t, ' name ')) # Note: The property ' name ' is required in quotation marks Truein [4]: Print (hasattr (t, ' Hello ')) # method is also a property of class true

GetAttr (object, name[, default])

Gets the object's property or method (name), if it exists, prints the default value if it is not present, the default value is optional, the default value does not exist the Error object does not have the attribute;

In [1]: Class Test (object):   ...:     name = ' hkey '   ...:     def hello (self):   ...:         print (' Hello ', Self.name): [   2]: t = Test () in [3]: Print (getattr (t, ' name ')) Hkeyin [4]: Print (getattr (t, ' hello ')) <bound met Hod Test.hello of <__main__. Test object at 0x000001499524ee80>>in [5]: Print (getattr (t, ' age '))------------------------------------------- --------------------------------attributeerror                            Traceback (most recent) < Ipython-input-5-bd4a642cfb8c> in <module> ()----> 1 print (getattr (t, ' age ') # without this property or method Attributeerror: ' Test ' object has no attribute ' age ' in [6]: Print (getattr (t, ' age ', 20)) # Set default value 20

SetAttr (object, name, values)

Assigns a value to the object's property, and if the property does not exist, first create the re-assignment

# object does not exist attribute (age), new attribute with SetAttr ' age ' in [1]: Class Test (object):   ...:     name = ' hkey '   ...:     def hello (sel f):   ...:         print (' Hello ', self.name)   ...: in [2]: T = Test () in [3]: Print (hasattr (t, ' age ')) Falsein [4]: Setatt R (T, ' age ', a) in [5]: Print (hasattr (t, "age")) Truein [6]: Print (getattr (t, ' age ')) 20# object existence attribute (name), overwrite original property value with SetAttr In [1]: Class Test (object):   ...:     name = ' hkey '   ...:     def hello (self):   ...:         print (' Hello ', Self.name)   : In [2]: T = Test () in [3]: Print (hasattr (t, ' name ')) # use Hasattr to check if object exists with the ' name ' property, true for existence Truein [4]: SetAttr (t, ' name ', ' Superman ') # SetAttr re-assigns the ' name ' property to ' Superman ' in [5]: Print (getattr (t, ' name ')) # Use GetAttr to get ' nam The value of the E ' property Supermanin [6]: Print (t.name) # directly invokes the Name property of the instance ' t ' Superman

From the above example, it is worth noting that if an object already has a property and again uses SetAttr to assign a value to the property, the property will change.

Hasattr (), GetAttr (), SetAttr () Usage scenarios

* Decoupling the program as a reflection *

In [1]: Class Test (object):   ...:     def __init__ (self):   ...:         self.x = 1   ...:         self.y = 2   ...: c8/> ...:     def sum (self): ...:         print (self.x + self.y)   ...   :     def sub (self):   ... :         print (SELF.X-SELF.Y)   ...: in [2]: T = Test () in [3]: While True:   ...:     cmd = input ('--'). Strip ()   ...:     if hasattr (t, cmd): # ' hasattr ' to determine if ' cmd ' property exists   ...:         func = getattr (t, cmd) # getattr get ' cmd ' genus The value of the sex ...   :         func () # executes this property   ...:     else:   ...:         setattr (t, cmd, t.sum) # If you enter a property name that does not exist, use ' SetAttr ' re-assigned ' cmd ' to ' t.sum ' ...    :         func = getattr (t, cmd)  # GetAttr Get the value of ' cmd ' property ...   :         func () # Execute this property ...   : # execution Result:-->SUM3-->SUB-1-->DDDDDD3

[Python] hasattr (), GetAttr (), SetAttr () three relationships and their use

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.