2017-10-16 58 views
0

对于一个类的方法,我想以下行为在方法默认参数中使用self的方法?

>>class A: 
>> def __init__(self, x): 
>>  self.x = x 
>> def func(self, x = self.x): 
>>  print(x) 
>>a = A(5) 
>>a.func(2) 
2 
>>a.func() 
5 

但我得到这个错误的func()声明:

Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "<stdin>", line 4, in A 
NameError: name 'self' is not defined 

是否有实现这一行为,建议这样做?

回答

3

使用标记值; None通常就足够了。

class A: 
    def __init__(self, x): 
     self.x = x 
    def func(self, x=None): 
     if x is None: 
      x = self.x 
     print(x) 

如果由于某种原因None可能是一个有效的参数,您可以创建自己的标记。

_sentinel = object() 
class A: 
    def __init__(self, x): 
     self.x = x 
    def func(self, x=_sentinel): 
     if x is _sentinel: 
      x = self.x 
     print(x) 
2

你不能指self在函数声明,因为在这一点上确实self不存在(因为错误说)。惯用的方法是:

def func(self, x = None): 
    if x is None: 
     x = self.x 
    print(x) 

或许:

def func(self, x = None): 
    print(x or self.x) 

(虽然注意到falsey是不一样的None并可能因此表现不同)

+0

不要使用'not';如果x是0或false,或者空列表或任何可能被视为False的其他值,该怎么办?您正在专门查找确切的对象“无”。 – chepner

+0

因此我的脚注。 – deceze

+0

解释为什么这是一个糟糕的主意并没有真正证明它首先被提出。 – chepner