默认为python类方法中的类变量?

rya*_*lon 3 python class default-value

我正在编写一个类方法,如果没有提供其他值,我想使用类变量

def transform_point(self, x=self.x, y=self.y):
Run Code Online (Sandbox Code Playgroud)

但是......这似乎不起作用:

NameError: name 'self' is not defined
Run Code Online (Sandbox Code Playgroud)

我觉得有一种更聪明的方法可以做到这一点.你会怎么做?

Mar*_*ers 5

您需要使用sentinel值,然后将其替换为具有所需实例属性的值.None是个不错的选择:

def transform_point(self, x=None, y=None):
    if x is None:
        x = self.x
    if y is None:
        y = self.y
Run Code Online (Sandbox Code Playgroud)

请注意,函数签名只执行一次 ; 您不能将表达式用于默认值,并期望每次调用函数时都会更改这些值.

如果你必须要能够设置xyNone那么你需要使用一个不同的,独特的单值设置为默认.object()在这种情况下,使用一个实例通常是一个伟大的哨兵:

_sentinel = object()

def transform_point(self, x=_sentinel, y=_sentinel):
    if x is _sentinel:
        x = self.x
    if y is _sentinel:
        y = self.y
Run Code Online (Sandbox Code Playgroud)

现在你也可以打电话.transform_point(None, None)了.