Inheritence Within Nested Classes

Hello, I am trying to implement code to talk to an arbitrary waveform generator. The end goal is to talk to multiple channels of two generators simultaneously to compare their precisions.

I want to make a nested class Channel within an outer class Generator. I want the inner class Channel to contain within it various functions to talk to the specified channel of the specified generator. In order to do this, I would need the created object in the inner class Channel to be able to read the name assigned to the outer object. I would expect the code to look similar to that below.

class Generator:
    def __init__(self, name):
        self.name = name

    class Channel:
        def __init__(self, number):
            self.number = number

        def sine(self, [actual parameters for function]):
            *talk to generator from here - requires variable 'Generator.name'

gen1 = Generator("name of generator")
c1 = gen1.Channel(1)
c1.sine([actual parameters for function])

I’ve tried adding super() and making the nested class a child class, but nothing seems to work. I can’t seem to get the name of the generator automatically passed to the functions within the nested object. Any help would be appreciated.

That variable does not exist. gen1.name does, the name is an instance variable. So you need the instance, but the instance of Channel has no knowledge of the “enclosing instance”. If you want that, you need to pass it into the __init__ method. That is one of the reasons why nested classes are very little used in Python.

Make Channel a not nested class and pass the generator instance gen1 when constructing its instances.

1 Like