Home > Net >  Refer to a supercalss from the class body
Refer to a supercalss from the class body

Time:05-12

I've got some code where I need to refer to a superclass when defining stuff in a derived class:

class Base:
    def foo(self):
        print('foo')

    def bar(self):
        print('bar')


class Derived_A(Base):
    meth = Base.foo


class Derived_B(Base):
    meth = Base.bar


Derived_A().meth()
Derived_B().meth()

This works, but I don't like verbatim references to Base in derived classes. Is there a way to use super or alike for this?

CodePudding user response:

Does this work for you?

class Base:
    def foo(self):
        print('foo')

    def bar(self):
        print('bar')


class Derived_A(Base):
    def __init__(self):
        self.meth = super().foo

class Derived_B(Base):
    def __init__(self):
        self.meth = super().bar


a = Derived_A().meth()
b = Derived_B().meth()

CodePudding user response:

You'll need to lookup the method on the base class after the new type is created. In the body of the class definition, the type and base classes are not accessible.

Something like:

class Derived_A(Base):
    def meth(self):
        return super().foo()

Now, it is possible to do some magic behind the scenes to expose Base to the scope of the class definition as its being executed, but that's much dirtier, and would mean that you'd need to supply a metaclass in your class definition.

  • Related