Python Forum

Full Version: Can we access instance variable of parent class in child class using inheritance
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am pasting my code below:-

class A:
    def __init__(self,i=100): 
      self.i=100
   

class B(A): 
   def __init__(self,j=0): 
      self.j=j 


b=B()
print(b.j)
print(b.i)
I have 2 class A and B . B is inheriting class A so according to the concept of inheritance base class acquires property of parent class so Instance variable i must be accessible to class B . But it is giving me an error that :
Error:
Traceback (most recent call last): File "D:/PYTHON/jljl.py", line 16, in <module> print(b.i) AttributeError: 'B' object has no attribute 'i'
Why this is giving error.
you forgot to initialize the instance of A in B
class A:
    def __init__(self,i=100): 
      self.i=100
    
 
class B(A): 
   def __init__(self,j=0):
       A.__init__(self)
       self.j=j 


b=B()
print(b.j)
print(b.i)
Not that relevant when your class inherits from single class, but in any case better to use super()

class A:
    def __init__(self, i=100): 
        self.i=100
    
 
class B(A): 
   def __init__(self, j=0):
        super().__init__()
        self.j=j 
 
 
b=B()
print(b.j)
print(b.i)
some external resources
https://realpython.com/python-super/
https://stackoverflow.com/questions/2228...-in-python
You need to call __init__ from A in B:
class B(A): 
   def __init__(self, i, j=0): 
      A.__init__(self, i)
      self.j=j