有没有一种方法可以在类内保留私有类变量,并将其用作非默认变量的默认值(在类外不定义该值的情况下)?
示例:
class a:
def __init__(self):
self.__variable = 6
def b(self, value = self.__variable):
print value
有没有一种方法可以在类内保留私有类变量,并将其用作非默认变量的默认值(在类外不定义该值的情况下)?
示例:
class a:
def __init__(self):
self.__variable = 6
def b(self, value = self.__variable):
print value
你在过度思考这个问题:
class a:
def __init__(self):
self.__variable = 6
def b(self, value=None):
if value is None:
value = self.__variable
print value
self.__variable
是实例变量,而不是类变量。None
并在函数体中添加if arg is None: arg = real_default
,这样可以解决问题)。__variable
。这就是为什么我强烈建议你删除一个下划线。 - user395760property
包装器。)如果我想要那种编译时检查的级别,我就不会使用动态类型语言。 - Karl KnechtelNone
成为可接受参数的范围之内,您可以创建一个自定义的标识值,在代码中不被用于其他任何目的。否则,b
永远不会返回 value
或 None
。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
b
,就会使用默认值。