Object Oriented - Reflection

Built-in functions: 
1.isinstance: Determine whether an object is related to a class
class A:pass
class B(A):pass
a = B()
print(isinstance(a,B)) #True
print(isinstance(a,A)) #True
print(type(a) is B) #True
print(type(a) is A) #False
2. issubclass (subclass name, parent class name): Detect the inheritance relationship and return True to indicate the inheritance relationship
class A:pass
class B(A):pass
class C(B):pass
print(issubclass(C,B))#True
print(issubclass(C,A))#True

 reflection

Reflection: Manipulate object-related properties in the form of strings, use the variable name of string data type to access a name in a namespace , find an attribute, you can directly find the value of this property, and find a method to find the method's value memory address.

4 built-in functions of reflection:

1.hasatter: Determine if there is an attribute or method in a namespace

class A:
    role = 'Person'
    def func(self):
        print('*'*self)

print(hasattr(A,'r')) # False
print(hasattr(A,'role')) # True
print(hasattr(A,'func')) # True
ret = input('>>>')
if hasattr(A,ret):
    print(getattr(A,ret))
if hasattr(A,ret):
    func = getattr(A,ret)
    func(12)
2.getatter: Get the value of an attribute or method from a namespace, the method needs to be called.
class A:
    role = 'Person'
    def func(self):
        print('*'*self)
ret = input( ' >>> ' )
 print (getattr(A, ' role ' )) #Find an attribute in A's namespace, you can directly find the value of this attribute 
f = getattr(A, ' func ' ); f(3) #Find a method from the namespace of A, and find the memory address of this method 
A.func(1)
  • Classes use names from the class namespace: getattr(classname, 'name')
  • The object uses the methods and attributes that the object can use: getattr(object name, 'name')
  • class A:
        role = 'Person'
        def __init__(self):
            self.money = 500
        def func(self):
            print('*'*5)
    a = A()
    getattr(a, ' func ' )()
     print (getattr(a, ' money ' )) #getattr(object name, 'name')
  • The module uses the name in the module: getattr(module name, 'name')
  • import time
    time.time()
    print(time.time)
    print(getattr(time,'time'))
    
    import them
    getattr(os,'rename')('user','user_info')
  • Use your own name in your own module: impoart sys     getattr(sys.modules['__main__'],name)
  • def login():
         print ( ' Execute the login function ' )
     def register():
         print ( ' Execute the register function ' )
    
    import sys #The content related to the python interpreter is in the sys module 
    print (sys.modules[ ' __main__ ' ]) #Find your own module (py file) 
    func = input( ' >>> ' )
    getattr(sys.modules['__main__'],func)()

 3.setatter: add and modify

 4.delatter: delete

class A:
    def __init__(self,name):
        self.name = name
    def wahaha(self):
        print('wahahaha')

a = A( ' alex ' )
 # a.age = 18 
# print(a.__dict__) 
setattr(a, ' age ' ,18) #Add an attribute 
print (a. __dict__ ) # {'age': 18, ' name': 'alex'} 
setattr(a, ' name ' , ' taibao ' ) #Modify an attribute 
print (a. __dict__ ) # {'age': 18, 'name': 'taibao'} 
delattr(a, ' age ') #delete an attribute
print(a.__dict__) #{'name': 'taibao'}

 built-in method

The len() built-in method corresponds to the built-in function __len__

class A:
    def __init__(self,name,age,sex,cls):
        self.name = name
        self.age = age
        self.sex = sex
        self.cls = cls
    def __len__(self):
        return len(self.__dict__)

a = A ( ' alex ' , 18, ' man ' , 2 )
 print (len (a)) # 4 
a.hobby = '烫 头' 
print (len (a)) # 5

The hash() built-in method corresponds to the built-in function __hash__

class A:
    def __init__(self,name,age,sex,cls):
        self.name = name
        self.age = age
        self.sex = sex
        self.cls = cls
    def __hash__(self):
        return 1
a = A('alex',18,'man',2)
print(hash(a)) # 1

 

Guess you like

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