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
4 Answers 4
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).
3 Comments
self.a.self.demo() in A wouldn't address the issue, since it'd still get B.demo. If you were to go with that route, you'd need to explicitly invoke A.demo(self). I'd say using different names is a better solution, but the code is contrived enough and has enough other design issues that it's hard to talk about what it "should" do.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)
Comments
It is because instance variable b is not initiated within __init__ of A
Comments
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()
self.a = None. Fist - you will never getAttributeError, second - you will have cleaner code with all your instance variables declared in the same place.