accessing superclass methods from subclass

Chris Rebert clp2 at rebertia.com
Sat May 8 20:05:44 EDT 2010


On Sat, May 8, 2010 at 4:50 PM, ben <thomasstruth at gmail.com> 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?

The way classes work in Python, C2 isn't actually created until after
its body suite has been executed, so that's why Python can't find f1.

Additionally, it makes no sense to call an *instance* method such as
f1() in a class context. Or in Java-speak: you can't call a non-static
method in a static context.

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list