The previous blog briefly introduced the basic knowledge of the class. The following describes some common methods of the class. An obvious sign of the so-called magic method is that the method name is enclosed by _ underscores. The previous blog briefly introduced the basic knowledge of the class. The following describes some common methods of the class. An obvious sign of the so-called magic method is that the method name is enclosed by _ underscores.
(1) _ init _
If you do not need to reload or override this method, the system will automatically call the system's default init method. if you rewrite this method to meet your needs, the method you override will automatically overwrite the default method of the system.
Class Ball: def _ init _ (self, name): self. name = name def kick (self): print ("My name is % s. damn it, who kicked me ...... "% self. name) a = Ball ("potato"). kick ()
After self-rewriting the init method, we can enter a parameter when instantiating an object.
class Rectangle: def __init__(self,x,y): self.x=x self.y=y def getPeri(self): return (self.x+self.y)*2 def getArea(self): return self.x * self.yrect=Rectangle(3,4)print(rect.getArea())print(rect.getPeri())
Purpose: delete an object.
Class C: def _ init _ (self): print ("I'm _ init _, I was called") def _ del _ (self): print ("I am _ del _ method, I was called") c1 = C () c2 = c1c3 = c2del c3del c2del c1
Let's talk about several common magic methods first, and then we will continue to add them.
The above is the content of the magic methods in class 13 of the zero-Basic Python beginners. For more information, see PHP Chinese network (www.php1.cn )!