accessing superclass methods from subclass

TFH pan-news at infocentrality.co.uk
Sun May 9 07:39:13 EDT 2010


On Sat, 08 May 2010 16:50:11 -0700, ben wrote:

> Why doesn't this work:
> 
> class C1:
>     def f1(self):
>         print("f1")
> 
> class C2(C1):
>     f1()
> 
> 
> It throws this error:
> 
> Traceback (most recent call last):
>   File "./c1.py", line 7, in <module>
>     class C2(C1):
>   File "./c1.py", line 8, in C2
>     f1()
> NameError: name 'f1' is not defined
> 
> 
> f1() is an attribute of class C1, C2 inherits C1, so why can't it see
> it?
> 
> thanks!

Try this:

class C1:
    def f1(self):
        return "From C1: f1"

class C2(C1):
    def f2(self):
        return self.f1()

c2 = C2()

print c2.f2()

regards

Trevor



More information about the Python-list mailing list