The content of this section
1, Isinstance (OBJ,CLS) and Issubclass (Sub,super)
2. Reflection
3, __setattr__,__delattr__,__getattr__
I, Isinstance (OBJ,CLS) and Issubclass (Sub,super) |
1. Isinstance (obj,cls) Check if obj is an object of class CLS
Class Foo (object): passobj = Foo () print (Isinstance (obj, Foo)) # True
2, Issubclass (sub, super) check if the sub class is a derived class of super class
Class Foo (object): passclass Bar (foo): passprint (Issubclass (Bar, Foo)) # must be a class, not an instance
1. The concept of reflection was first proposed by Smith in 1982, which refers to the ability (introspection) of a program to access, detect, and modify its own state or behavior.
The proposal of this concept soon triggered the research on the application of reflectivity in Computer science field. It is first used in the field of programming language design, and has achieved achievements in Lisp and object-oriented.
2. Python Object-oriented reflection: Manipulate object-related properties in the form of a string. All things in Python are objects (you can use reflection)
Four functions that can be self-reflective
The following methods apply to classes and objects (everything is an object, and the class itself is an object). In the case of object, the same applies to class
hasattr (object, name) # to determine whether an object has a method or property that has a name string corresponding to it
GetAttr (object, Name, None) # Gets the method or property corresponding to the name string in object, none returns none
SetAttr (object, name, value) # Sets the value of the name string in object, without name, new property
delattr (oject, name) # Removes the method or property corresponding to the name character in Ojbect, and will error if no Name
classBlackmedia (object): Feature=" Business" def __init__(self, Name, address): Self.name=name Self.address=AddressdefSell_house (self):Print("I am the black agent [%s], to buy a house! "%self.name)defRent_house (self):Print("I am the black agent [%s], to rent it! "%self.name) B1= Blackmedia ("Huaxia Real Estate","on the edge of imperial City")#detect if a property is includedPrint(Hasattr (B1,'name'))#where ' name ' is a string * * * *Print(Hasattr (B1,'Sell_house'))#True#Get Propertiesn = GetAttr (B1,'name')Print(n) Func= GetAttr (B1,'Rent_house')Print(func)#<bound method Blackmedia.rent_house of <__main__. Blackmedia object at 0x0000008f538344e0>>func ()#GetAttr (B1, ' aaaaa ') does not exist on the errorPrint(GetAttr (B1,'AAAA','does not exist'))#Setting PropertiesSetAttr (B1,'SB', True) SetAttr (B1,'Show_name',LambdaSelf:self.name +'Black Property')Print(B1.__dict__)Print(B1.show_name (B1))#Delete PropertyDelattr (B1,'SB')#delattr (B1, ' Show_name11 ') no errorPrint(B1.__dict__)
four ways to use an example
classFoo (object): Staticfield=" old boy" def __init__(self): Self.name='Wupeiqi' deffunc (self):return 'func'@staticmethoddefBar ():return 'Bar'Print(GetAttr (Foo,'Staticfield'))Print(GetAttr (Foo,'func'))Print(GetAttr (Foo,'Bar'))
class is also an object
3. The benefits of reflection
Advantage One: The interface can be defined in advance, the interface is only after the completion of the actual execution, this implementation of Plug and Play, which is actually a ' late binding '
class ftpclient: ' FTP client, but still have the ability to implement specific ' def __init__ (SELF,ADDR): Print (' connecting server [%s]' %addr) self.addr=addr
programmer A does not implement the function
#From module Import ftpclientF1=ftpclient ('192.168.1.1')ifHasattr (F1,'Get'): Func_get=getattr (F1,'Get') Func_get ()Else: Print('----> This method does not exist') Print('dealing with other logic') does not affect Alex's code writing
Programmer B Pre-Call the interface of a
Benefit Two: Dynamic import module (based on Reflection current module member)
Third, __setattr__,__delattr__,__getattr__ |
classfoo:x=1def __init__(self,y): Self.y=ydef __getattr__(self, item):Print('----> from getattr: The attribute you are looking for does not exist') def __setattr__(self, Key, value):Print('----> from setattr') #Self.key=value #这就无限递归了, you think about it. #Self.__dict__[key]=value #应该使用它 def __delattr__(self, item):Print('----> from delattr') #del Self.item #无限递归了Self.__dict__. Pop (item)#__setattr__ Adding/Modifying a property will trigger its executionF1=foo (10)Print(F1.__dict__)#because you rewrite the __setattr__, any assignment operation will trigger its operation, you do not write anything, is not assigned at all, unless you directly manipulate the property dictionary, otherwise you can never assign a valueF1.z=3Print(F1.__dict__)#__delattr__ is triggered when a property is deletedF1.__dict__['a']=3#we can directly modify the property dictionary to complete the operation of adding/modifying propertiesdelf1.aPrint(F1.__dict__)#__getattr__ fires only when a property is called with a point and the property does not exista demonstration of the usage of f1.xxxxxx three
Three usage demo
Python Automation Development-Object Oriented (ii)