温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

python不同版本中的_new_有什么区别

发布时间:2020-12-10 15:46:55 来源:亿速云 阅读:180 作者:Leah 栏目:开发技术

python不同版本中的_new_有什么区别?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

new方法接受的参数虽然也是和init一样,但init是在类实例创建之后调用,而 new方法正是创建这个类实例的方法。

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

Python3和 Python2中__new__使用不同

Python3的写法

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

如果Python3的写法跟Python2写法一样,那么倒数第二行会报错

"TypeError: object() takes no parameters"

根据上面的运行结果我们可以发现,在python3中强行使用python2的写法是不可行的。

Python __new__()知识点扩充

__new__() 是一种负责创建类实例的静态方法,它无需使用 staticmethod 装饰器修饰,且该方法会优先 __init__() 初始化方法被调用。

一般情况下,覆写 __new__() 的实现将会使用合适的参数调用其超类的 super().__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__(): <class '__main__.demoClass'> ('abc',) {}
__init__(): <__main__.demoClass object at 0x0000026FC0DF8080> abc
__new__(): <class '__main__.demoClass'> ('xyz',) {}
__init__(): <__main__.demoClass object at 0x0000026FC0DED358> xyz
0 2
1 2

关于python不同版本中的_new_有什么区别问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI