Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Correct way of returning new class object (which could also be extended)

I am trying to find a good way for returning a (new) class object in class method that can be extended as well.

I have a class (classA) which has among other methods, a method that returns a new classA object after some processing

class classA:
   def __init__(): ...

   def methodX(self, **kwargs):
      process data
      return classA(new params)

Now, I am extending this class to another classB. I need methodX to do the same, but return classB this time, instead of classA

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class classB(classA):
   def __init__(self, params):
      super().__init__(params)
      self.newParams = XYZ
   
   def methodX(self, **kwargs):
      ???

This may be something trivial but I simply cannot figure it out. In the end I dont want to rewrite the methodX each time the class gets extended.

Thank you for your time.

>Solution :

Use the __class__ attribute like this:

class A:
    def __init__(self, **kwargs):
        self.kwargs = kwargs

    def methodX(self, **kwargs):
        #do stuff with kwargs
        return self.__class__(**kwargs)

    def __repr__(self):
        return f'{self.__class__}({self.kwargs})'

class B(A):
    pass

a = A(foo='bar')
ax = a.methodX(gee='whiz')
b = B(yee='haw')
bx = b.methodX(cool='beans')

print(a)
print(ax)
print(b)
print(bx)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading