How to set the value class returned by __new__ without using super?

I want to Bbe a subclass of some class A, and I want to override A.__new__ 1 . Typically, my code for this would have this basic structure:

class B(A):
    def __new__(cls, ...):
        ret = super(B, cls).__new__(cls, ...)

        # modify ret as needed

        return ret  # type(ret) is cls

    # ...

So type(B(...))really B. (Note: ellipses in super(B, cls).__new__(cls, ...)should not represent the same elements as ellipses in the signature B.__new__.)

But suppose now that I want to use the value returned by some factory method / function method A_Factory(which returns a type object A) as the initial value for the variable retin the constructor. If I just encoded this:

class B(A):
    def __new__(cls, ...):
        ret = A_Factory(...)

        # modify ret as needed

        return ret  # type(ret) is A

... then it type(B(...))will be A, not B.

ret B.__new__ , type(B(...)) B , , C of B, type(C(...)) C?


1 , __new__, , .

+4
1

__class__ cls, __new__:

class A(object):
    def __init__(self):
        self.x = 2

def A_Factory():
    return A() 

class B(A):
    def __new__(cls):
        ret = A_Factory()

        ret.__class__ = cls  # Override the class.

        return ret  # type(ret) is cls

class C(B):
    pass


if __name__ == "__main__":
    b = B() 
    print(b.x)
    print(type(b))
    print(isinstance(b, B)) 
    print(isinstance(b, A))
    c = C()
    print(type(C))

:

2
<class '__main__.B'>
True
True
<class '__main__.C'>

. , __class__, :

__class__ , . , . :

  • dict
  • GC
  • , , , , dict weaklist (, , )

__slots__, . , Python. Python int tuple - , C, .

+1

All Articles