tags:

views:

98

answers:

3

i want to to pass class method as and a default argument to another class method, so that i can re-use the method as a @classmethod

@classmethod
class foo:
 def func1(self,x):
  do somthing;
 def func2(self, aFunc = self.func1):
  # make some a call to afunc
  afunc(4)

this why when the method func2 is called within the class aFunc defaults to self.func1, but i can call this same function from outside of the class and pass it a different function at the input.

i get
NameError: name 'self' is not defined

for those who want more detail:

so here is my setup

 class transmissionLine:  
     def electricalLength(self, l=l0 , f=f0, gamma=self.propagationConstant,deg=False):  

but i want to be able to call electricalLength with a different function for gamma, like

transmissionLine().electricalLength (l,f,gamma=otherFunc)
+6  A: 

Default argument values are computed during function definition, not during function call. So no, you can't. You can do the following, however:

def func2(self, aFunc = None):
    if aFunc is None:
        aFunc = self.func1
    ...
doublep
I really don't know that I completely understand the question that he is asking, but you have certainly identified the cause of the error that he is seeing.
Adam Crossland
+1  A: 

You should write it like this:

class Foo(object):
    @classmethod
    def func1(cls, x):
        print x
    def func2(self, afunc=None):
        if afunc is None:
            afunc = self.func1
        afunc(4)

Though it would be helpful if you gave a little more info on what you are trying to do. There is probably a more elegant way to do this without classmethods.

Brendan Abel
@alex -- the above is hard to read in a comment. Edit your question and add it there
Adam Crossland
+1  A: 

The way you are trying wont work, because Foo isnt defined yet.

class Foo:  
  @classmethod
  def func1(cls, x):
    print 'something: ', cls, x

def func2(cls, a_func=Foo.func1):
 a_func('test')

Foo.func2 = classmethod(func2)

Foo.func2()
evilpie
Hey i know thats not really a pythonic cool looking solution, but the question was "can i pass class method as and a default argument to another class method", and yes you could.
evilpie
You are passing a function, not method binding here. Method binding already includes the first argument (in this case it is `cls`), but function doesn't. Try to use your suggestion and you will see that call to `a_func` won't work because there's not enough arguments.
doublep
I don't see why this was downvoted. It looks viable to me. doublep is wrong, the code runs in Python 2.6 as written.
Jason R. Coombs
I was wrong indeed. Didn't consider that `self` is not needed for a classmethod and `Foo.func1` is actually a method binding for a classmethod. Even for a normal method it is a binding though it cannot be called without class object.
doublep