有没有办法在类中保留私有类变量,仍然使用它作为非默认变量的默认值(不在类之外定义该值)?
示例:
class a:
def __init__(self):
self.__variable = 6
def b(self, value = self.__variable):
print value
答案 0 :(得分:14)
你是在思考这个问题:
class a:
def __init__(self):
self.__variable = 6
def b(self, value=None):
if value is None:
value = self.__variable
print value
答案 1 :(得分:4)
self.__variable
是一个实例变量,而不是类变量。None
和将if arg is None: arg = real_default
添加到函数体中,确实有效。)答案 2 :(得分:4)
值得添加的是,如果希望None
在允许的参数范围内,则可以创建一个自定义的sentinal值,该值不会用于代码中的任何其他用途。如果不这样做,value
,None
将永远无法从b
返回。
UseDefault = object()
# Python 3? Otherwise, you should inherit from object unless you explicitly
# know otherwise.
class a:
def __init__(self):
self._variable = 6
def b(self, value=UseDefault):
if value is UseDefault:
value = self._variable
print value
现在None
可以传递给b
而不会导致默认使用。