_ del_
The destructor method of the class, it is executed when the object is recycled, and the main function is to release resources (memory file process, etc.)
Because of the Python memory recycling mechanism, the execution time of Python's del method is uncertain, so it is not recommended to use the destructor method in Python.
classBar(object):
def __del__(self):print("Was recycled! ~")
a =Bar()
a.__del__() #Active call is useless, because the reference count is not zero, and the resource gc will not be reclaimed
print("A has been deleted")print(a)
del a
# print(a)
_ dict_
_ slots_
classBar(object):
__ slots__ =('name','gender')
def __init__(self, name='monkey'):
self.name = name
self.gender ='male'
a =Bar()
a.age =18 #Adding properties dynamically will report an error.
print(a.name)
_ str_
Must return a str type. When printing the object, the returned str will be printed instead of the default self.str
: return: <main…. object at 0x1084b7208
classBar(object):
def __str__(self):return"Bar"
a =Bar()print(a) # Bar
_ repr_
Convert the object into an interpreter-friendly form. It is closely related to the eval() method. Usually repr() calls the object's repr method, which returns an interpreter-friendly object description in string format, eval( ) Can convert the return value of repr() into the original object.
This thing is very powerful. It is the most direct manifestation of polymorphism. Almost any class object implements it, but each returned result is different.
_ class_
_ class_ allows to call the methods of the class and manipulate the attributes of the class through the object, that is, object.class can get the class of this object
After getting the class, you can perform new instantiation operations on the properties of the class and call the methods of the class.
classBar(object):
name ='monkey'
a =Bar()print(a.__class__.name) #Allow access to classes through instantiated objects
_ doc_
Print the docstring of an object or class or method
classBar(object):"""
A simple show class!"""
name ='monkey'
def get_name(self):"""
getclassargument name
"""
return self.__class__.name
a =Bar()print(a.__class__.__doc__)print(a.__class__.get_name.__doc__)
# A simple show class!
#
#
# getclassargument name
_ base_
Used to return the parent class of the class
_ bases_
Used to return the inheritance list of the class
classLady(object):""" """classSmall(object):""" """classSmallLady(Small, Lady):""""""print(Lady.__base__) # <class'object'print(SmallLady.__bases__) # (<class'__main__.Small',<class'__main__.Lady')
_ iter_
Must return an iterable object
This object needs to implement the next method.
_ next_
Each time the next value of the iterator or an iteration exception is returned to terminate the iteration.
_ len_
Each time the next value of the iterator or an iteration exception is returned to terminate the iteration.
classListMeta(type):
def __call__(self, data,*args,**kwargs): #Make self, that is, the instantiated class, a callable List()Here self refers to the class itself to be instantiated
self.__init__(self,data)return self
def __str__(self):
result = self.clean_data(self) #It is List that can return the desired list format to convert the object into a human-friendly string
result ='[{}]'.format(result[:-1])return result
def __repr__(self):return'List({})'.format(self.__str__()) #Converted to an interpreter-friendly string
def __iter__(self): #Return an object that implements the iterator protocol
return self #It implements__next__
def __next__(self): #Implement the iterator protocol, each time it returns the next value or an iteration terminates the iteration abnormally
if self.index =len(self.data):
raise StopIteration
else:
value = self.data[self.index]
self.index +=1return value
def __len__(self): #Returns the length of the object, len()The function will execute the object__len__method
return self.len
classList(metaclass=ListMeta):
def __init__(self, data):
self.data = data
self.index =0
self.len =len(self.data)
l =List([1,2,3,4,5,6,7])print(l)print(len(l))for i in l:print(i)
_ hash_
Must return an int type of data, and can uniquely represent this object. This is very important.
_ getattribute_
_ getattr_
_ setattr_
When setting an attribute in the form of a point attribute name, the setattr method will be called. This method needs to write the corresponding relationship between the attribute name and the attribute value into the relation dictionary dict. If you override this method, don't forget to manually update the object attribute dictionary.
classStorage(object):
def __init__(self, name):
self.name = name #transfer__setattr__method
def __getattribute__(self, item): #Call this method before each attribute is accessed
print('getattribute: %s'% item)
ret = True
if item =='error':
raise AttributeError(r'Error ~ "error"') #It is still executed if an error is reported~
else:
ret = object.__getattribute__(self, item)return ret
def __getattr__(self, item):print('getattr: %s'% item)try:return self.__dict__[item]except(IndexError, KeyError)as e:print('No attribute %s '% e)return'%s is error'% item
def __setattr__(self, key, value):print('setattr: %s '% key)
self.__dict__.update({key:value})
file =Storage('file')
name = file.error #transfer__getattr__method
# setattr: name
# getattribute: __dict__
# getattribute: error
# getattr: error
# getattribute: __dict__
# No attribute 'error'
The above is the detailed content of the topic of Python magic methods. For more information about Python magic methods, please pay attention to other related articles on ZaLou.Cn!
Recommended Posts