(python) built-in functions related to reflection

Two built-in methods not related to reflection:

isinstance(obj,cls) determines whether an object is an instance of a class.

issubclass(cls, object) determines whether a class is a subclass of a class.

The built-in functions related to reflection are described below.

The following four functions are specially used to manipulate the properties of classes and objects. To manipulate the properties of classes and objects through strings, this operation is called reflection.





 
 
class People:
    country='China'
    def __init__(self,name):
        self.name=name
    def tell(self):
        print('%s is aaa' %self.name)

obj=People('monicx')
#hasattrfunction
print('country'in People.__dict__)#Determine whether the attribute exists
print(hasattr(People,'country'))
print(hasattr(People,'tell'))
print(hasattr(People,'name'))

#getattrfunction
print(getattr(People,'country'))#China
print(getattr(People,'tell',None))#<function People.tell at 0x00000000026BA950>

#setattrfunction
# People.x=11111
setattr(People,'x',11111)
print(People.x)
#obj.age=18
setattr(obj,'age',18)

#delattrfunction
People.country #
delattr(People,'country')
print(People.__dict__)
#del obj.name
delattr(obj,'name')
print(obj.__dict__)

Here is a simple application scenario of reflection.

When the user enters a command, it can be reflected to the corresponding function:

class Foo:
    def run(self):
        while True:
            cmd=input('cmd>>:').strip()#Reflect user input to its function
            # print('%s run....'%cmd)
            if hasattr(self,cmd):
                func=getattr(self,cmd)
                func()

    def download(self):
        print('download....')

    def upload(self):
        print('upload')
obj=Foo()
obj.run()

The running result is:


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325752320&siteId=291194637