Home > front end >  Python super class / sub class infinite loop
Python super class / sub class infinite loop

Time:11-30

I am a student and new to Python. I have the following code:

class A:
  ...

  def fit(self, X, y):
     ...
     return self

  def transform(self, X):
    ...
    return transformed_X

  def fit_transform(self, X, y):
    return self.fit(X, y).transform(X)

class B(A):
  ...

  def fit(self, X, y):
    transformed_X = super().fit_transform(X, y)
    ...

which I think leads to an infinite loop (B calls fit_transform in A which then calls fit in B again etc.). Is this correct? How do I get around this? I want the call super().fit_transform(X, y) in B to return what it would if the object was just of type A.

Thank you.

CodePudding user response:

As you pointed out super().fit_transform(X, y) is equivalent to A.fit_transform(self, X, y) which calls self.fit and self is an instance of B. Hence the infinite recursion.

one way to go would be to hard_code the usage of A.fit in A.fit_transform as such:

class A:
    
    def fit(self, X, y):
        print("A fit")
        return self

    def transform(self, X):
        print("A transform")
        return "here we are"

    def fit_transform(self, X, y):
        print("A fit_transsform")
        return A.fit(self, X, y).transform(X)

class B(A):
  

  def fit(self, X, y):
    print("B fit")
    transformed_X = super().fit_transform(X, y)
    return transformed_X

which prints:

B fit
A fit_transsform
A fit
A transform
'here we are'

However this code is very ugly and your classes/methods might not be designed properly (maybe compose rather than inherit since B seems to use A rather than being an A)

CodePudding user response:

If you only want B.fit_transform to return as if it was of type A, how about just:

class B:
    def fit_transform(self, X, y):
        return A().fit_transform(X, y)
  • Related