魔法方法: 构造和析构
【Python教程】《零基础入门学习Python》_哔哩哔哩_bilibili
- __init__(self[,…]) --- 返回值一定是none
-
>>> class A: def __init__(self): return 2022 >>> a2 = A() Traceback (most recent call last): File "<pyshell#64>", line 1, in <module> a2 = A() TypeError: __init__() should return None, not 'int'
- __new__(cls[, …]) --- 实例化时真正第一个被调用的方法,它跟其他魔法方法不同,它的第一个参数不是 self 而是这个类(cls),而其他的参数会直接传递给 __init__ 方法的 一般不会去重写,只有在特殊的情况下,eg 继承了一个不可变的类,但是又需要做出修改时. __new__ 方法主要任务时返回一个实例对象.
-
>>> class CapStr(str): def __new__(cls, string): string = string.upper() #将调用字符串的upper()方法并赋给string return str.__new__(cls, string) #将新的string传给老的str的__new__方法,返回的对象给我们新的__new__()方法 >>> str1 = CapStr('i am just not capitalized!') >>> str1 'I AM JUST NOT CAPITALIZED!'
-
''' Celsius to Fahrenheit ''' class C2F(float): def __new__(cls, arg=0.0): return float.__new__(cls, arg * 1.8 + 32) >>> print(C2F(32)) 89.6
-
定义一个类继承于 int 类型,并实现一个特殊功能:当传入的参数是字符串的时候,返回该字符串中所有字符的 ASCII 码的和(使用 ord() 获得一个字符的 ASCII 码值)。 class Nint(int): def __new__(cls, arg=0): if isinstance(arg, str): total = 0 for each in arg: total += ord(each) arg = total return int.__new__(cls, arg)
- __del__(self) --- 垃圾回收机制使用, 当del删除实例对象时,如果这个对象的所有引用都被删除时就会被垃圾回收机制干掉,这个时候才会调用内置的__del__方法。__del__ 方法是当垃圾回收机制回收这个对象的时候调用的
-
>>> class C: def __init__(self): print('This is init method, I am called') def __del__(self): print('This is del method, I am called') >>> c1 = C() This is init method, I am called >>> c2 = c1 >>> c3 = c2 >>> del c1 >>> del c2 >>> del c3 This is del method, I am called