小甲鱼零基础python 笔记之 构造和析构(P42)

 魔法方法: 构造和析构

【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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值