开发者

Not Possible to Reference self in a Method Declaration?

I wanted to write a method with an argument that defaults to a member variable like so:

def method(self, arg1=0, arg2=self.member):

Apparently this is not allowed. Should I write it a different way, or perhaps use a value of arg开发者_StackOverflow中文版2 to signal when to use the member variable?


Yep, use a sentinel -- e.g.:

class Foo(object):
    _sentinel = object()
    def method(self, arg1=0, arg2=_sentinel):
        if arg2 is self._sentinel: arg2 = self.member
        ...
    ...

note that you need barename _sentinel in the def, but self._sentinel in the body of the method (since that's how scoping works out in class bodies vs method bodies;-).


def method(self, arg1=0, arg2=None):
    if arg2 is None:
        arg2 = self.member
    ...
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜