[Tutor] Class Inheritance -> NameError

Christopher Arndt chris.arndt at web.de
Thu Dec 1 04:09:55 CET 2005


Tim Johnson schrieb:
> The following code snippet is meant to test inheritance:
> class test:
>     def __init__(self,v):
>         self.__val = v
>     def val(self):
>         print self.__val
> class sub(test):
>     def __init__(self):
>         val()
> The following console session has an error:
> 

Beware test.__val is a 'private' attribute. See
http://www.python.org/doc/current/tut/node11.html#SECTION0011600000000000000000
for an explanation.

>>>>T = mylib.test('hello')
>>>>s = mylib.sub()
> 
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
>   File "mylib.py", line 1612, in __init__
>     val()
> NameError: global name 'val' is not defined
> 
> ## what do I need to do to make the 'test method visible
> ## class 'sub?

Surely you mean the 'val' method (see the traceback)?

it lives in the namespace of the class 'test'. So if you want to call it as a
class method:

>>> test.val(instance)

if you want to call it as an instance method:

>>> instance = sub()
>>> instance.val()

resp. in the class and sub-classes itself:

>>> self.val()


HTH, Chris


More information about the Tutor mailing list