[Tutor] Class Inheritance -> NameError

Liam Clarke-Hutchinson Liam.Clarke-Hutchinson at business.govt.nz
Thu Dec 1 04:18:33 CET 2005


Hi Tim, 

Either - 

class test:
    def __init__(self,v):
        self.__val = v
    def val(self):
        print self.__val


class sub(test):
    def __init__(self, v):
        test.__init__(v)
        self.val()

or - 

class sub(test):
    def __init__(self, v):
        test.__init__(v)
        test.val()




That will resolve your calling the method problem, but self.__val won't
inherit (I think). I don't recommend using double underscored variables
unless there's a really good reason, C# et al be damned.

Oh, and if self.__val / val is set by the superclasses __init__ method, then
you'll need to call it specifically, or otherwise you'll get a
UnboundLocalError, because self.__val/val won't exist.



Liam Clarke-Hutchinson

-----Original Message-----
From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf
Of Tim Johnson
Sent: Thursday, 1 December 2005 3:46 p.m.
To: tutor at python.org
Subject: [Tutor] Class Inheritance -> NameError


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:
>>> 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?
thanks
tim

-- 
Tim Johnson <tim at johnsons-web.com>
      http://www.alaska-internet-solutions.com
_______________________________________________
Tutor maillist  -  Tutor at python.org
http://mail.python.org/mailman/listinfo/tutor

A new monthly electronic newsletter covering all aspects of MED's work is now available.  Subscribers can choose to receive news from any or all of seven categories, free of charge: Growth and Innovation, Strategic Directions, Energy and Resources, Business News, ICT, Consumer Issues and Tourism.  See http://news.business.govt.nz for more details.




http://www.govt.nz - connecting you to New Zealand central & local government services

Any opinions expressed in this message are not necessarily those of the Ministry of Economic Development. This message and any files transmitted with it are confidential and solely for the use of the intended recipient. If you are not the intended recipient or the person responsible for delivery to the intended recipient, be advised that you have received this message in error and that any use is strictly prohibited. Please contact the sender and delete the message and any attachment from your computer.


More information about the Tutor mailing list