>>> # Magic Method
>>>
>>> # Magic methods are always surrounded by double underscores , such as __init__
>>> # Magic method is all about object-oriented Python
>>> # The Magic of magical methods is reflected in their ability to be automatically invoked at the right time
>>>
>>> # __init__ (self[,...]) is equivalent to other language constructs, which are automatically invoked when a class object is instantiated
>>> # The return value of the __init__ method is none, never write return
>>> class Rectangle: Span style= "color: #0000ff;" >def __init__ (Self,x,y): self.x = x self.y = y def Getperi (self): # Get the perimeter of the rectangle
return (self.x + self.y) * 2
def
Getarea ( Self):
return self.x *
Self.y ;>> rect = Rectangle (3,4
) >>>
14>>> Rect.getarea () 12>>>
>>> # __init__ () method is not the first method called, but __new__ (cls[,...])
>>>
>>> # __new__ method, we usually seldom go to rewrite it
>>>
>>> # There is a situation where you need to rewrite the __new__ method, which is when you inherit an immutable class and you need to modify it
>>>
class capstr (str): def__new__(cls,string): string=string.upper () return str.__new__(cls,string) >>> a = Capstr ("I Love you!< /c15>")>>> a'I Love you! '>>>
>>> # If the __init__ method and the __new__ method are constructors, then the __del__ method is the destructor method
>>> # The __del__ (self) method is automatically called when the object is to be destroyed, which is used when the garbage collection mechanism
>>>
The >>> # __del__ method does not mean that we execute del obj and will be called, but all references to it will be called after Del.
>>>classC:def __init__(self):Print("I am the __init__ method, I was called ...") def __del__(self):Print("I am the __del__ method, I was called ...") >>> C =C () I am the __init__ method, I was called ...>>> C2 =C>>>delC>>>delC2 I was the __del__ method, I was called ...
Python Learning notes 009_ construction and destruction