开发者

Can I pass class method as and a default argument to another class method

开发者 https://www.devze.com 2022-12-29 19:20 出处:网络
I want to pass class method as and a default argument to another class method, so that I can reuse the method as a @classmethod:

I want to pass class method as and a default argument to another class method, so that I can reuse 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 is 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

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)


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
    ...


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()


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消