__在对象创建过程中没有调用new\uuuuuuuuu

2024-04-26 04:03:10 发布

您现在位置:Python中文网/ 问答频道 /正文

案例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对象?你知道吗


Tags: 方法newreturnobjectdef情况argskwargs
2条回答

我猜它和Python2中的new and old style classes有关:

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中,行为是相同的,无论是否显式继承自object

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”两次

我在找文件,最后在这里找到了: https://staging2.python.org/dev/peps/pep-0253/

The type object has a new slot, tp_new, which can act as a factory for instances of the type. Types are now callable, because the tp_call slot is set in PyType_Type (the metatype); the function looks for the tp_new slot of the type that is being called.

再加上@devforfu的答案,在过去,__new__并不存在。它是随着新样式类的添加而添加的。你知道吗

相关问题 更多 >