python函数的默认参数

wim*_*wim 4 python lambda arguments function

如何访问qux内部方法?我是否真的必须在体内重新定义它foo(),或者有没有办法从中导入它self

class Baz(object):

    qux = lambda x : x + '_quux'

    def foo(self, bar=qux('fred')):
        print bar

        print qux('waldo')
        # NameError: global name 'qux' is not defined

        print Baz.qux('waldo')
        # TypeError: unbound method <lambda>() must be called with Baz instance as first argument (got str instance instead)

        print Baz.qux(self, 'waldo')
        # TypeError: <lambda>() takes exactly 1 argument (2 given)

        print self.qux('waldo')
        # TypeError: <lambda>() takes exactly 1 argument (2 given)                
Run Code Online (Sandbox Code Playgroud)

Ign*_*ams 7

如果您希望能够访问课程中的方法,则必须使用classmethodstaticmethod.

class Baz(object):
  qux = staticmethod(lambda x : x + '_quux')
Run Code Online (Sandbox Code Playgroud)

但是不要这样做.

  • 使用`bar = None`并检查方法体中的`bar是None`. (2认同)