__new__ 和 __init__
class Foo(object): def __new__(cls, *args, **kwargs): # 1.根据类创建对象,并返回 # 2.执行返回的对象的__init__方法 # return '张三' # 执行张三(字符串对象)的__init__ 方法 return object.__new__(cls) # 创建Foo对象,调用该对象的__init__方法 def __init__(self,x): print('x的值:', x) self.x = x # def __str__(self): # print(self.x) obj = Foo('李四') print(obj)
结果:
return '张三'
>> 张三
return object.__new__(cls)
>> 123
>> <__main__.Foo object at 0x000001DA618D7278>
作者: Deaseyy
出处: http://www.cnblogs.com/Deaseyy/
新手一枚,请大佬们多多赐教!
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出, 原文链接