reflex
Reflection: attributes mapped to objects through strings
class People(): def __init__(self, name, age): self.name = name self.age = age def talk(self): print('Name:%s,Age:%s' % (self.name, self.age)) p = People('ysg', 21) # To determine whether the attribute exists in the object, the actual judgment is p.__dict__ ['name'] print(hasattr(p, 'name')) # result: True # Take to 'name' Value in print(getattr(p, 'name', None)) # result: ysg print(getattr(p, 'names', None)) # result: None print(getattr(p, 'talk', None)) # <bound method People.talk of <__main__.People object at 0x0000020EDF705278>> # modify 'name' Value in setattr(p, 'name', 'ysging') # p.name = 'ysging' print(p.name) # result: ysging # delete 'name' object delattr(p, 'age') # del p.age print(p.__dict__) # result:{'name': 'ysging'}
There is a need to call methods through user input
Example
class People(): def __init__(self, name, age): self.name = name self.age = age def run(self): while 1: val = input('>>>') if hasattr(self, val): func = getattr(self, val, None) func() def talk(self): print('Name:%s,Age:%s' % (self.name, self.age)) p = People('ysg', 21) p.run() # Result # >>>talk # Name:ysg,Age:21
Benefits of reflection:
Benefit 1: implement pluggable mechanism
There are two programmers, one is lili, the other is egon. lili needs to use the classes written by egon when writing the program, but egon has gone on his honeymoon with his girlfriend, and has not finished his classes yet. lili thought of reflection, and lili can continue to complete his code generation by using the reflection mechanism. After egon comes back from his honeymoon, lili can continue to complete the definition of classes and realize the functions lili wants.
In a word, the advantage of reflection is that you can define the interface in advance, and the interface will be implemented only after it is completed. This implements plug and play, which is actually a kind of "late binding". What do you mean? That is, you can write the main logic in advance (only define the interface), and then later implement the function of the interface
Benefit 2: dynamic import module (based on reflection of current module members)
Built in method
isinstance(obj,cls) checks whether obj is a cls like object
class Foo(): pass obj = Foo() g = 123 print(isinstance(obj, Foo)) # True print(isinstance(g, Foo)) # False
issubclass(sub, super) checks whether the sub class is a derived class of the super class
class Foo(): pass class A(Foo): pass class B(): pass print(issubclass(A, Foo)) # True print(issubclass(B, Foo)) # False
item series: types of imaging Dictionaries
class Foo(): def __init__(self, name): self.name = name def __getitem__(self, item): print('getitem...') return self.__dict__.get(item) def __setitem__(self, key, value): print('setitem...') print(key,value) # name ysging self.__dict__[key] = value def __delitem__(self, key): del self.__dict__[key] f = Foo('ysg') print(f.__dict__) # {'name': 'ysg'} # Value print(f['name']) # ysg # set up f['name'] = 'ysging' print(f.name) # ysging # delete del f['name'] print(f.__dict__) # {}
__str__
In general, print out as memory address
class People(): def __init__(self, name, age): self.name = name self.age = age p = People('ysg', 22) print(p) # <__main__.People object at 0x000002C168D952E8>
After using str, print results can be customized
class People(): def __init__(self, name, age): self.name = name self.age = age def __str__(self): return '<name:%s,age:%s>' % (self.name, self.age) p = People('ysg', 22) print(p) # <name:ysg,age:22>
__Del UU: if a del UU method is defined inside the class, it will be triggered automatically when the object is deleted, and then the object will be deleted
python will only recycle the resources of the object itself, not the data related to the object
class Open(): def __init__(self,file): print('open file...') self.file = file def __del__(self): print('Recycle resources related to objects: self.close()') #Here you can write data related to objects, such as resources in the operating system f = Open('config.py') print('-------main-------')
Destruct method that automatically triggers execution when an object is released in memory.
Note: if the generated object is only at the python program level (user level), there is no need to define "del". If the generated object also initiates a system call to the operating system, that is, an object has two kinds of resources at the user level and the kernel level, for example (open a file, create a database link), the system resources must be recycled while the object is cleared, That's what we use__
Typical application scenarios:
Create a database class and use this class to instantiate the database link object. The object itself is stored in user space memory, while the link is managed by the operating system and stored in kernel space memory
At the end of the program, python will only reclaim its own memory space, that is, user state memory, while the operating system resources are not recycled. Therefore, we need to customize "del" to initiate a system call to close the database link to the operating system before the object is deleted to reclaim the resources