原代码:
# -*- coding: utf-8 -*- class Person(object): def __new__(cls, name, age): print('__new__ called.') return super(Person, cls).__new__(cls, name, age) def __init__(self, name, age): print('__init__ called.') self.name = name self.age = age def __str__(self): return '<Person: %s(%s)>' % (self.name, self.age) if __name__ == '__main__': name = Person('xxx', 24) print(name)期望输出:
__new__ called. __init__ called. <Person: xxx(24)>实际输出:
报错原因: 上述为python2的写法,而博主用的是python3。
# __new__()修改前 return super(Person, cls).__new__(cls, name, age) # __new__()修改后 return super(Person, cls).__new__(cls)debug后:
# -*- coding: utf-8 -*- class Person(object): def __new__(cls, name, age): print('__new__ called.') return super(Person, cls).__new__(cls) def __init__(self, name, age): print('__init__ called.') self.name = name self.age = age def __str__(self): return '<Person: %s(%s)>' % (self.name, self.age) if __name__ == '__main__': name = Person('xxx', 24) print(name) __new__ called. __init__ called. <Person: xxx(24)>总结:
1.创建一个类的顺序:先创建对象(__new__方法) 然后 初始化对象(__init__方法) 2.python2和python3对super函数不同的写法:python3__new__()不用参数。