Nested classes that inherit from the outer parent's nested classes in Python 3

652 views Asked by At

Suppose I have the following class in Python 3:

class CoolCar:
    @classmethod
    def myWheels(cls):
        cls.Wheels().out()
    class Wheels:
        def __init__(self):
            self.s = "I'm round!"
        def out(self):
            print(self.s)

All well and good. Now I want a derived class:

class TerribleTank(CoolCar):
    class Wheels(CoolCar.Wheels):
        def __init__(self):
            self.s = "I'm square!!"

This works as I would expect:

CoolCar.myWheels()
TerribleTank.myWheels()

But what's bothering me is that I have to write CoolCar twice in the definition of TerribleTank. So I tried this:

class TerribleTank(CoolCar):
    class Wheels(super().Wheels):
        def __init__(self):
            self.s = "I'm square!!"

Which does not work. Now, I know it doesn't work because super() is looking for a first-argument self/cls to begin its search.

So finally my question: Is there something like this that works, so that I don't need to explicitly write that second CoolCar?

1

There are 1 answers

4
zmo On

What about:

class CoolCar:
    @classmethod
    def myWheels(cls):
        cls.Wheels().out()
    class Wheels:
        def __init__(self):
            self.s = "I'm round!"
        def out(self):
            print(self.s)

class TerribleTank(CoolCar):
    class Wheels(TerribleTank.Wheels):
        def __init__(self):
            self.s = "I'm square!!"

>>> TerribleTank.myWheels()
I'm square!!

basically when you inherit CoolCar in TerribleTank, you set up TerribleTank.Wheels as a reference to CoolCar.Wheels, until you shadow it with your own new definition of it within the TerribleTank definition. So I believe that matches your expectations of not having CoolCar twice in TerribleBank definition ☺

HTH