First page Back Continue Last page Overview Graphics

Inheritance and Attributes

class A(object):

def __init__(self):

self.x = "public"

self._x = "protected"

self.__x = "private"

class B(A):

def __init__(self):

A.__init__(self)

def show_attributes(self):

print(self.__x)

if __name__ == "__main__":

b = B()

b.show_attributes()

class A(object):

def __init__(self):

self.x = "public"

self._x = "protected"

self.__x = "private"

def _m(self):

print("This is _m!")

def __m(self):

print("This is _m!")

class B(A):

def __init__(self):

A.__init__(self)

def call_A_methods(self):

self._m()

self.__m()

if __name__ == "__main__":

b = B()

b.call_A_methods()

Traceback (most recent call last):

File "/home/data/workspace/test/test2.py", line 15, in <module>

b.show_attributes()

File "/home/data/workspace/test/test2.py", line 11, in show_attributes

print(self.__x)

AttributeError: 'B' object has no attribute '_B__x'

This is _m!

Traceback (most recent call last):

File "/home/data/workspace/test/test2.py", line 20, in <module>

b.call_A_methods()

File "/home/data/workspace/test/test2.py", line 16, in call_A_methods

self.__m()

AttributeError: 'B' object has no attribute '_B__m'