2

I know C++ and Java and I am unfamiliar with Pythonic programming. So maybe it is bad style what I am trying to do.

Consider fallowing example:

class foo:
        def a():
                __class__.b() # gives: this is foo
                bar.b() # gives: this is bar
                foo.b() # gives: this is foo
                # b() I'd like to get "this is bar" automatically

        def b():
                print("this is foo")

class bar( foo ):
        def b( ):
                print("this is bar")

bar.a()

Notice, that I am not using self parameters as I am not trying to make instances of classes, as there is no need for my task. I am just trying to refer to a function in a way that the function could be overridden.

Johu
  • 626
  • 7
  • 15

2 Answers2

5

What you want is for a to be a classmethod.

class Foo(object):
    @classmethod
    def a(cls):
        Foo.b() # gives: this is foo
        Bar.b() # gives: this is bar
        cls.b() # gives: this is bar
    @staticmethod
    def b():
        print("this is foo")

class Bar(Foo):
    @staticmethod
    def b():
        print("this is bar")

Bar.a()

I've edited your style to match the Python coding style. Use 4 spaces as your indent. Don't put extra spaces in between parenthesis. Capitalize & CamelCase class names.

A staticmethod is a method on a class that doesn't take any arguments and doesn't act on attributes of the class. A classmethod is a method on a class that gets the class automatically as an attribute.

Your use of inheritance was fine.

agf
  • 171,228
  • 44
  • 289
  • 238
  • Thanks! Your answer had also some info I didn't know to ask. Now I know, [this question](http://stackoverflow.com/questions/136097/what-is-the-difference-between-staticmethod-and-classmethod-in-python) also gives some useful info about these decorators. – Johu Aug 09 '11 at 10:17
  • I'd suggest you read about them on the built in functions page of the docs as well, http://docs.python.org/library/functions.html#classmethod – agf Aug 09 '11 at 10:19
0

Quote from the Execution Model:

The scope of names defined in a class block is limited to the class block; it does not extend to the code blocks of methods – this includes generator expressions since they are implemented using a function scope.

This mean that there is no name b in the scope of function a. You should refer to it via class or instance object.

Roman Bodnarchuk
  • 29,461
  • 12
  • 59
  • 75