1, Reflection Reflection: Use the name of the string type to manipulate the variable reflection there is no security problem, to manipulate the existing variables in memory #反射对象中的属性和方法
class A: price =20print(GetAttr (A,'price'))
#反射对象的属性
class A: def func (self): Print (' infunc'=='Alex' =getattr (A,'name')# value taken from the string of the variable name print(ret)
#反射对象的方法
RET =getattr (A,'func') ret ()
#反射类的方法:
if hasattr (A,'func')): GetAttr (A,'func ') ()
#反射类的属性
class A: price =20print(GetAttr (A,'price'))
#反射模块的属性
Import my Print (GetAttr (My,'day'))
#反射自己模块中的变量
Import SYS Print (GetAttr (sys.modules['__main__'),'year') GetAttr (sys.modules['__main__'),'qqxing' )()
SetAttr setting/modifying variables
class A: Pass setattr (A,'name','Alex') Print (A,name)
DELATTR Deleting a variable
Delattr (A,'name')
2,__str__ and __repr__
Changing the object's string display __str__,__repr__
Self-Customizing formatted string __format__
# Double Down Method # obj.__str__ str (obj)# obj.__repr__ repr (obj)
classTeacher:def __init__(self,name,salary): Self.name=name Self.salary=Salarydef __str__(self):return "Teacher ' s object:%s"%Self.namedef __repr__(self):returnSTR (self.__dict__) deffunc (self):return 'Wahaha'Nezha=teacher ('Nazha', 250)Print(Nazha)Print(repr (Nezha))Print('>>>%r'%nezha)
# object has a __str__ that, once called, returns the call to this method # The memory address of the object l = [1,2,3,4,5] # Instantiates an object that instantiates a list class
print (L) # %s str () Direct printing is actually going __str__ # %r repr () is actually walking __repr__ # repr is a spare tire for STR, but STR is not able to make a repr spare tire # print (obj)/'%s '%obj/str (obj), the obj.__str__ method is actually called internally, and if the Str method has, then he must return a string # If there is no __str__ method, first find the __repr__ method in this class, No more __str__ in the parent class. # repr (), only find __repr__, if no parent class is found
classClasses:def __init__(self,name): Self.name=name Self.student= [] def __len__(self):returnLen (self.student)def __str__(self):return 'Classes'Py_s9= Classes ('python full stack phase 9') Py_s9.student.append ('two elder brother') Py_s9.student.append ('Brother Tai')Print(Len (PY_S9))Print(PY_S9)
# __del__ class A: def __del__ (self): # destructor: Do some finishing work before deleting an object == open () # opening a file first opens a file in the operating system and gets the file operator in memory. del a # A.F got the file operator disappears in memory del a # del This method was executed, and the variable was deleted
#__call__classA:def __init__(self,name): Self.name=namedef __call__(self):" "Print all the properties in this object: return:" " forKinchSelf.__dict__: Print(K,self.__dict__[K]) a= A ('Alex')()
Python: Object-oriented advanced