Chris
Chris

Reputation: 217

Inheritance and accessing parent class in unbound method in python

I have this class with an unbound method and a static class inside:

class ClassA():
    class Foo():
        pass

    def getFoo():
        return ???.Foo

Now, if I inherit a ClassB from ClassA how do I get ClassB.getFoo() to return ClassB.Foo without explicitly implementing ClassB.getFoo()? Returning super().Foo doesn't work, writing ClassA.Foo doesn't work either obviously.

Upvotes: 0

Views: 468

Answers (2)

Liam Deacon
Liam Deacon

Reputation: 894

Just to add my own thoughts on this: In addition to @Ned Batchelder's answer, you can use static methods to achieve a similar goal.

class ClassA():
    class Foo():
       def fooTest(self):
         print("Hello from {}!".format(self.__name__))

  @staticmethod
  def getFoo():
    return ClassA.Foo

class ClassB(ClassA):
    pass

And test with:

>>> Foo = ClassB.getFoo()
>>> foo = Foo()
>>> foo.fooTest()
Hello from Foo!

This to me demonstrates the beauty of the python language - there are usually multiple ways of solving the same problem...

Upvotes: 0

Ned Batchelder
Ned Batchelder

Reputation: 375564

Your getFoo should be a classmethod:

class ClassA():
    class Foo():
        pass

    @classmethod
    def getFoo(cls):
        return cls.Foo

Class methods are passed their class as their first argument, similar to how instance methods are passed the instance as the first argument. When you subclass ClassA, the proper class is passed.

Upvotes: 4

Related Questions