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):

pass

def show_attributes(self):

print(self.x)

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"

class B(A):

def __init__(self):

A.__init__(self)

def show_attributes(self):

print(self.x)

print(self._x)

if __name__ == "__main__":

b = B()

b.show_attributes()

Traceback (most recent call last):

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

b.show_attributes()

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

print(self.x)

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

public

protected