__新的uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu

2024-05-08 01:33:25 发布

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

调用__new__方法时遇到困难。你知道吗

在创建A()的实例时,如果输入值小于10,则返回B()的实例。但是实例是在没有运行__new____init__方法的情况下创建的,这是为什么?你知道吗

class A (object):
    def __init__ (self, IP, s):
        print 'arrived to init a'
        self.IP=IP
        print self.IP
        print s
    def __new__ (cls, IP, s):
        print "arrived to new a"
        if IP>10:
            self = object.__new__ (cls)
            return self  # return n
        else:
            return super (cls, A).__new__ (B)

class B(object):
    def __init__(self,d,s,ar):
        print 'arrived to b'
        self.ip=d
        print self.ip
        print s
        print ar
    def __new__(cls,d,s,ar):
        print 'arrived to new b' 
        self = object.__new__(cls)
        return self  # return n
    def __repr__(self):
        return 'B({}, ..., ...)'.format(getattr(self, 'ip', '<missing>'))

a = A(10 ,"a")
print a

这个输出

arrived to new a
B(<missing>, ..., ...)

而不是

arrived to new a
arrived to new b
arrived to b
10
'a'
?
B(10, ..., ...)

Tags: to实例方法selfipnewreturnobject
1条回答
网友
1楼 · 发布于 2024-05-08 01:33:25

您要求object.__new__在此处创建一个新实例:

return super (cls, A).__new__ (B)

所以A.__new__在这里返回一个B()的实例,而因为它返回一个新的B()实例,而不是一个新的A()实例,B.__init__()将永远不会被调用;类型需要匹配。参见^{} documentation

If __new__() returns an instance of cls, then the new instance’s __init__() method will be invoked like __init__(self[, ...]), where self is the new instance and the remaining arguments are the same as were passed to __new__().

B()不是A的实例,因此不调用__init__B.__new__未被调用,因为您通过请求object.__new__创建实例来显式绕过它。你知道吗

直接在A.__new__中调用B()

    if IP>10:
        self = object.__new__ (cls)
        return self  # return n
    else:
        return B(IP, s, 42)

您需要传入三个参数;我为第三个参数编了42。你知道吗

因为调用了B(),所以将调用B.__new__。因为B.__new__返回B的实例,所以__init__方法也将被调用。你知道吗

演示:

>>> A(10 ,"a")
arrived to new a
arrived to new b
arrived to b
10
a
42
B(10, ..., ...)

相关问题 更多 >