views:

51

answers:

2

I want my classes X and Y to have a method f(x) which calls a function func(x, y) so that X.f(x) always calls func(x, 1) and Y.f(x) always calls func(x, 2)

class X(object):
    def f(self, x):
        func(x, 1)

class Y(object):
    def f(self, x):
        func(x, 2)

But I want to place f in a common base class B for X and Y. How can I pass that value (1 or 2) when I inherit X and Y from B? Can I have sth like this (C++ like pseudocode):

class B(object)<y>:  # y is sth like inheritance parameter
    def f(self, x):
        func(x, y)

class X(B<1>):
    pass

class Y(B<2>):
    pass

What techniques are used in Python for such tasks?

+6  A: 

Python is more flexible than you give it credit.

I think you want something like this:

class B(object):
    def f(self,x):
        func(x, self.param)

class X(B):
    param=1

class Y(B):
    param=2

NB

  • note the method f has self as the first parameter.
  • the param= lines are class variables.
quamrana
+1  A: 

You could use a class decorator (Python 2.6 and up) if you just want to add a common function to several classes (instead of using inheritance).

def addF(y):
    def f(self, x):
        return "Hello", x, "and", y

    def decorate(cls):
        cls.f = f
        return cls

    return decorate


@addF(1)
class X(object):
    pass

@addF(2)
class Y(object):
    pass

print X().f("X")
print Y().f("Y")

>>> 
Hello X and 1
Hello Y and 2
truppo
Seems to be the solution! Thank you!
netimen