class Programmer(object):
def __new__(cls, *args, **kwargs):
print 'call __new__ method'
print args
print super(Programmer,cls).__new__(cls, *args, **kwargs)
def __init__(self,name,age):
print 'call __init__ method'
self.name = name
self.age = age
if __name__ == '__main__':
programmer = Programmer('Albert',25)
print programmer.__dict__
运行结果:
"C:\Program Files\Anaconda2\python.exe" C:/Users/Administrator/PycharmProjects/untitled/classlearning4-2.py
Traceback (most recent call last):
call __new__ method
('Albert', 25)
<__main__.Programmer object at 0x00000000022F2C50>
File "C:/Users/Administrator/PycharmProjects/untitled/classlearning4-2.py", line 17, in <module>
print programmer.__dict__
AttributeError: 'NoneType' object has no attribute '__dict__'
print programmer.__dict__
代码最后一行的__dict__,因为原本的__init__方法还没有执行。因此此时只是执行了实例化的第一步__new__,通过下面dir语句可以看出此时没有__init__过的对象确实没有成员变量(属性)。
print dir(programmer)
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
print programmer.__init__
最后一句改为上面__init__将会成功打印出对象的属性
重写new这个魔术方法的时候,需要返回一个对象,将print改为return即可
这个确实怪,怎么老师的代码有问题,还拿出来教人啊,
改了之后,只跳出来以下的代码,没有出现属性啊?望大神帮忙解决,如何打印出属性?
print programer.__init__ <method-wrapper '__init__' of NoneType object at 0x000000001E29D7D8>