Python Forum
Base class variables are not accessible - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Base class variables are not accessible (/thread-13762.html)



Base class variables are not accessible - Prabakaran141 - Oct-31-2018

Hi,

I just want to understand, why I'm getting below error in inheritance?
Error:
Traceback (most recent call last): File "inheritance.py", line 13, in <module> main() File "inheritance.py", line 10, in main print b_obj.aa AttributeError: 'B' object has no attribute 'aa'
This is my python code
class A(object):
    def __init__(self):
        self.aa = None

class B(A):
    def __init__(self):
        self.bb = None
def main():
    b_obj = B()
    print b_obj.aa

if __name__ == '__main__':
    main()



RE: Base class variables are not accessible - woooee - Oct-31-2018

The init function under A is never called so self.aa does not exist. https://www.python-course.eu/python3_inheritance.php


RE: Base class variables are not accessible - Prabakaran141 - Oct-31-2018

Hi Wooee,

Thanks for replying back. I thought __init__() is similar to a constructor in other programming language(c++) and so it will be called once we create a derived class object.


RE: Base class variables are not accessible - buran - Oct-31-2018

Python’s super() considered super! by Raymond Hettinger

Based on python print statement I guess you use python2. In this case this should work
class A(object):
    def __init__(self):
        self.aa = None

 
class B(A):
    def __init__(self):
        super(B, self).__init()__
        self.bb = None


def main():
    b_obj = B()
    print b_obj.aa

 
if __name__ == '__main__':
    main()
In python3 (and you should be using it, because python2 official support ends Jan, 1st 2020) same code will look like

class A(object):
    def __init__(self):
        self.aa = None

 
class B(A):
    def __init__(self):
        super().__init()__
        self.bb = None


def main():
    b_obj = B()
    print(b_obj.aa)

 
if __name__ == '__main__':
    main()