gpt4 book ai didi

python - __new__ 在对象创建中没有被调用

转载 作者:行者123 更新时间:2023-11-30 22:12:14 27 4
gpt4 key购买 nike

案例1:

class Person:
def __new__(cls, *args, **kwargs):
print "called"
return super(Person, cls).__new__(cls, *args, **kwargs)

p=Person()

案例2:

class Person(object):
def __new__(cls, *args, **kwargs):
print "called"
return super(Person, cls).__new__(cls, *args, **kwargs)

p=Person()

在第一种情况下,不会调用 __new__() 方法,但在第二种情况下会调用。

如果没有被调用,那么 Person 对象是如何创建的?

最佳答案

我猜这与 new and old style classes 有关。在Python2中:

Old-style classes don't actually have a __new__ method because for them __init__ is the constructor, so basically if we would have:

class A:

def __new__(cls):
print "A.__new__ is called" # -> this is never called

A()

the body of __new__ will never be executed in this case because it is not the purpose for old-style classes.

在 Python3 中,行为是相同的,无论您是否显式继承对象:

class Person1:
def __new__(cls, *args, **kwargs):
print("called")
return super(Person1, cls).__new__(cls, *args, **kwargs)


class Person2(object):
def __new__(cls, *args, **kwargs):
print("called")
return super(Person2, cls).__new__(cls, *args, **kwargs)


p1 = Person1()
p2 = Person2()

当从 3.x 调用时,这些应该打印“called”两次。

关于python - __new__ 在对象创建中没有被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51165504/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com