Skip to content
Advertisement

Share attributes/ variables between classes python

class Base(object):
    def __init__(self):
        print("Base created")
        a = "baseclass"

class ChildA(Base):
    def __init__(self):
        Base.__init__(self)
        b = "child a"

class ChildB(Base):
    def __init__(self):
        super(ChildB, self).__init__()
        c = "child b"
        print(a)
        print(b)

ChildA()
ChildB()
NameError: name 'a' is not defined

Advertisement

Answer

Your issue here is that you’re trying to access local variables instead of instance attributes.

Here’s how you should do it:

class Base():
    def __init__(self):
        print("Base created")
        # Note that you should use `self.a` instead of `a`
        self.a = "baseclass"

class ChildA(Base):
    def __init__(self):
        Base.__init__(self)
        # Use `self.b` instead of `b`
        self.b = "child a"

# Did you forget to inherit from `ChildA`?
class ChildB(ChildA):
    def __init__(self):
        # The `super()` call can be simplified
        super().__init__()
        # Use `self.c` instead of `c'
        self.c = "child b"

        # Access the instance variables using `self.`
        print(self.c)
        print(self.b)
        print(self.a)


ChildA()
ChildB()

From the console output:

Base created
Base created
child b
child a
baseclass
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement