python-Object-oriented 05 reflection

Source: Internet
Author: User

Reflection, mapping to object properties by string

?

Class people:country= ' China ' def __init__ (self,name,age): Self.name=name self.age=age def talk (sel f): Print ('%s is talking '%self.name) p = people ("GD", page) print (p.name) # p.__dic__[' name ']print (p.talk) # <bou nd method People.talk of <__main__. People an object at 0x00000000027b7470>>print (Hasattr (p, ' name ')) # True to determine if the object p has a name attribute, hasattr (), the first argument to the object, and the second argument Pass Property name Print (Hasattr (p, ' Talk1 ')) # Trueprint (GetAttr (p, ' name ')) # GD Gets the attribute in object P # print (GetAttr (p, ' name2 ')) # Attribu  Teerror: ' People ' object has no attribute ' name2 ' # getattr (), there is no corresponding attribute when, will error, we can pass in the third parameter print (GetAttr (p, ' name2 ', None)) # None so that when the property is not found, it will return None setattr (p, ' sex ', ' Machine Master ') print (p.sex) # machine master print (p.__dict__) # {' Name ': ' GD ', ' age ': 22, ' Sex ': ' Machine Master '}delattr (p, ' sex ') # Delete property print (p.__dict__) # {' Name ': ' GD ', ' age ': 22}# hasattr () getattr () Setatter () d Elattr () applies not only to objects, but also to class print (Hasattr (people, ' Country ')) # Trueprint (GetAttr (People, ' Country ')) # China

?

?

Application of Reflection

class Service:    def run(self):        while True:            cmd = input(">>:").strip()            if hasattr(self, cmd):                func = getattr(self, cmd)                func()    def get(self):        print('get......')    def put(self):        print('put.....')obj = Service()obj.run()# >>:get# get......# >>:put# put.....

python-Object-oriented 05 reflection

Related Article

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.