Reputation: 725
class A:
def __init__(self):
self.i = 0
def demo(self):
self.a=1
class B(A):
def __init__(self, j = 0):
super().__init__()
self.j = j
print(self.i)
self.demo()
def demo(self):
print(self.a)
def main():
b = B()
print(b.i)
print(b.j)
main()
why am i not able to access self.a inside class b does prefixing a variable with self. will make it an instance variable Thanks
Upvotes: 0
Views: 75
Reputation: 26688
Because you overwrite demo
method on B class
.
If you want to access self.a
add it to __init__
method of A
class or call parent demo
method like this:
def demo(self):
super().demo()
print(self.a)
Upvotes: 1
Reputation: 1017
Because class A.demo() is not executed:
class A:
def init(self):
self.i = 0
def demo(self):
self.a=1
class B(A):
def __init__(self, j = 0):
super().__init__()
self.j = j
print(self.i)
super().demo()
self.demo()
def demo(self):
print(self.a)
def main():
b = B()
print(b.i)
print(b.j)
main()
Upvotes: 0
Reputation: 49318
When you include a demo
method for both classes, the most recently-defined one masks the others. Since you define B
after you define A
but before you call any of the methods in A
, demo
will try to access a variable that was never defined. You should either call demo
within A
(in __init__
, probably), or change the name of demo
in B
to something unique, which will allow you to access both methods (probably the best approach, since they do different things and you want to make use of both).
Upvotes: 4
Reputation: 40624
It is because instance variable b
is not initiated within __init__
of A
Upvotes: 0