Today, I finally started to learn magic methods. I started watching it during the seminar last Monday, and I can't officially watch it until today. .
Review the old and learn the new, play steadily, don't rush
Chapter 12 Magical Methods
__init__(self) method
Two points to note:
class Rectangle:
def __init__(self,x,y): First make such a call to the variable description
self.x = x
self.y = y
def getperi(self):
return self.x + self.y def getarea( self): return self.x * self.y
The return value of the __init__ method must be None, not other
__new__(cls) method
Need to return an instance object
class Capstr(str):
def __new__(cls,string):
string = string.upper() all uppercase
return str.__new__(cls,string) return str.__new__(cls,string), which is a specific instance object
__del__(self)
When the object is to be destroyed, this method will be called, note: all variables related to this
(My simple understanding can only go here,,,)
BIF (builtin function or function) built-in function or method
int( ) integer
float( ) float
str( ) string
list( ) list
tuple( ) tuple
Inverse operation
__radd__(self,other)
However, it should be noted that the inverse operation is divided into active and passive. If the magic method of the a object is not implemented or does not support the corresponding operation, Python will automatically call the magic method of b
class Nint(int):
def __radd__(self,other):
return int.__radd__(self,other)
a = Nint (5)
b = Nint (3)
Then the result of a + b should be 5+3 = 8 because the magic method "+" of a triggers __add__
And 1 + b , the magic method of 1 cannot be found, so find the magic method of b, touch __radd__ , the result is b - 1 = 3 - 1 = 2
(In the inverse operation, self is b, other is 1, so it is b -1)
class Nint(int):
def __rsub__(self,other):
return int.__sub__(self,other)
a = Nint (5)
3 - a = ?
3 If the sub is not found, go to the rsub of a. At this time, a is self and 3 is other, that is, a - 3 = 5 - 3 = 2
Increment assignment operator
a = a + b
a + = b
unary operator
__neg__(self) defines the behavior of the positive sign
__pos__(self) defines the behavior of the minus sign
__abs__(self) takes the absolute value
__invert__(self) defines the behavior of inversion
Next time see 44 Simple customization
After-school exercises:
2 When do we need to explicitly write the __init__ method in the class?
When our instance object needs to have explicit initialization steps, we can deploy the initialization code in the __init__ method
class C2F(float):
def __new__(cls,arg=0.0):
return float.__new__(cls,arg*1.8+32)
Next time see 188 duck types