当前位置: 首页 > news >正文

python __new__方法

python __new__方法

python __new__方法,先于__init__方法执行

class A:def __init__(self):print('A init')class B(A):def __new__(cls, *args, **kwargs):print('B new')return super().__new__(cls)def __init__(self):super().__init__()print('B init')b = B()

new方法返回init的self对象

class CapStr(str):def __new__(cls, str_value: str):super_new = super().__new__(cls, str_value)print(id(super_new))return super_newdef __init__(self, str_value: str):print(id(self))cap_str = CapStr('guanxianseng')
print(cap_str)