JavaScript
x
20
20
1
class Base(object):
2
def __init__(self):
3
print("Base created")
4
a = "baseclass"
5
6
class ChildA(Base):
7
def __init__(self):
8
Base.__init__(self)
9
b = "child a"
10
11
class ChildB(Base):
12
def __init__(self):
13
super(ChildB, self).__init__()
14
c = "child b"
15
print(a)
16
print(b)
17
18
ChildA()
19
ChildB()
20
JavaScript
1
2
1
NameError: name 'a' is not defined
2
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:
JavaScript
1
29
29
1
class Base():
2
def __init__(self):
3
print("Base created")
4
# Note that you should use `self.a` instead of `a`
5
self.a = "baseclass"
6
7
class ChildA(Base):
8
def __init__(self):
9
Base.__init__(self)
10
# Use `self.b` instead of `b`
11
self.b = "child a"
12
13
# Did you forget to inherit from `ChildA`?
14
class ChildB(ChildA):
15
def __init__(self):
16
# The `super()` call can be simplified
17
super().__init__()
18
# Use `self.c` instead of `c'
19
self.c = "child b"
20
21
# Access the instance variables using `self.`
22
print(self.c)
23
print(self.b)
24
print(self.a)
25
26
27
ChildA()
28
ChildB()
29
From the console output:
JavaScript
1
6
1
Base created
2
Base created
3
child b
4
child a
5
baseclass
6