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

前端 未结 3 918
耶瑟儿~
耶瑟儿~ 2021-01-05 11:38

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
cl         


        
相关标签:
3条回答
  • 2021-01-05 11:49

    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
        ...
    
    0 讨论(0)
  • 2021-01-05 11:50

    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()
    
    0 讨论(0)
  • 2021-01-05 11:52

    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 讨论(0)
提交回复
热议问题