Can I pass a class method like the default argument to another class method

I want to pass the class method as well as the default argument to another class method so that I can reuse this method as @classmethod:

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

That is why when a method func2is called inside the class aFuncby default self.func1, but I can call this same function from outside the class and pass it another function in the input.

I get:

NameError: name 'self' 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 electricalLengthanother function for gamma, for example:

transmissionLine().electricalLength (l, f, gamma=otherFunc)
+5
source share
3 answers

, . , . :

def func2(self, aFunc = None):
    if aFunc is None:
        aFunc = self.func1
    ...
+9

:

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

, , . , classmethods.

+1

, , Foo .

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

All Articles