Python 2与Python 3中__new__方法的区别与用法
本文总结了Python 2与Python 3中__new__方法的语法差异。重点指出Python 3强制使用新式类写法,若沿用Python 2的super(Person, cls).__new__形式会报错。通过Person、Singleton及demoClass三个示例,展示了__new__作为静态方法的调用时机、参数传递及在单例模式中的应用。
核心差异:Python 2与Python 3的__new__写法
在Python中,__new__是负责创建类实例的静态方法,它优先于__init__被调用。虽然__new__无需使用staticmethod装饰器修饰,但其写法在Python 2和Python 3中存在显著差异。
Python 3强制要求使用新式类的写法。如果在Python 3中强行使用Python 2的super(Person, cls).__new__(cls, name, age)形式,解释器会抛出TypeError: object() takes no parameters错误。这是因为Python 3中所有类默认继承自object,且super()函数的调用方式已简化。
Python 2中的__new__实现
在Python 2中,__new__需要显式调用父类的__new__方法,并传递cls作为参数。以下是一个Person类的示例:
class Person(object):
"""Silly Person"""
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__':
piglei = Person('piglei', 24)
print piglei该代码展示了__new__如何接收参数并调用super(Person, cls).__new__。注意,这里必须传递cls给父类的__new__。
Python 3中的__new__实现
在Python 3中,super()可以不带参数调用,且__new__的写法更加简洁。以下是一个单例模式(Singleton)的实现示例:
class Singleton(object):
def __new__(cls,*args, **kwargs):
if not hasattr(cls,'_inst'):
print(cls)
cls._inst = super(Singleton, cls).__new__(cls)
return cls._inst或者更简洁的写法(Python 3推荐):
class Singleton(object):
def __new__(cls,*args, **kwargs):
if not hasattr(cls,'_inst'):
cls._inst = super().__new__(cls)
return cls._inst注意:在Python 3中,如果错误地使用了Python 2的写法(如super(Person, cls).__new__(cls, name, age)且name和age不是object接受的参数),会触发TypeError: object() takes no parameters。
__new__的高级应用:实例计数与修改
__new__在返回实例前可以修改实例属性。以下示例展示了如何在__new__中为每个实例分配唯一的编号:
class demoClass:
instances_created = 0
def __new__(cls,*args,**kwargs):
print("__new__():",cls,args,kwargs)
instance = super().__new__(cls)
instance.number = cls.instances_created
cls.instances_created += 1
return instance
def __init__(self,attribute):
print("__init__():",self,attribute)
self.attribute = attribute
test1 = demoClass("abc")
test2 = demoClass("xyz")
print(test1.number,test1.instances_created)
print(test2.number,test2.instances_created)该代码展示了__new__如何接收参数、创建实例、修改实例属性(instance.number)以及递增类变量(cls.instances_created)。注意,__init__在__new__之后被调用,用于初始化实例的其他属性。
总结
Python 3中__new__的写法更加简洁,推荐使用super().__new__(cls)。Python 2中需要显式传递cls给父类的__new__。理解这些差异有助于在不同Python版本中正确实现单例模式和其他高级类特性。
以上就是Python不同版本__new__方法差异的详细内容,更多关于Python__new__用法及单例模式实现资料请关注本站其它相关文章!
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









