Inheritance: a base class method that returns an instance of itself

My base class has a method that returns an instance of itself. When I write my subclass, is there a way to make this instance an instance of my subclass instead of the base class without changing the code of the base class or by rewriting the entire method of the base class into my subclass method?

Example:

class A:
    def __init__(self,x):
        self.x = x
    def add(self):
        self.x += 2
    def new(self,z):
        n = A(z)
        return n

class B(A):
    def __init__self():
        A.__init__(self,x)

Now if I do:

a = B(10)
b = a.new(4)

Then b will be an instance of A, not an instance of B, as I want it to be. In this simple example, I could just override the method in class B, but in my program that I don't want, it just breaks portability, because I cannot control the base class since it is part of another package.

Is there any way to do this?

+4
3

:

@classmethod
def new(cls, z):
    return cls(z)
+2

, :

def new(self,z):
    n = A(z)
    return n

:

def new(self, z):
    n = self.__class__(z)
    return n

, , , hardcoding , .

, , , :

  • , , .

, , . , : , , , API , , , . ( ), .

- . , , , , , B.

( ):

def new_new(self, z):
    n = self.__class__(z)
    return n

A.new = new_new
+1

__class__:

n = self.__class__(z)
return n

...

@jonrsharpe

0

Source: https://habr.com/ru/post/1532387/


All Articles