【问题标题】:Default to class variables in a python class method?默认为python类方法中的类变量?
【发布时间】:2013-02-22 14:55:42
【问题描述】:

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

def transform_point(self, x=self.x, y=self.y):

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

NameError: name 'self' is not defined

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

【问题讨论】:

    标签: python class default-value


    【解决方案1】:
    def transform_point(self, x=None, y=None):
        if x is None:
            x = self.x
        if y is None:
            y = self.y
    

    【讨论】:

    • 请注意,调用transform_point(obj) 将导致所有后续对transform_point 的调用使用xy 的默认参数None
    【解决方案2】:

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

    def transform_point(self, x=None, y=None):
        if x is None:
            x = self.x
        if y is None:
            y = self.y
    

    注意函数签名只执行一次;你不能使用表达式来表示默认值,并期望它们随着每次调用函数而改变。

    如果您能够将xy 设置为None,那么您需要使用不同的、唯一的单例值作为默认值。在这种情况下,使用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
    

    现在你也可以拨打.transform_point(None, None)了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-22
      • 2013-02-17
      • 1970-01-01
      • 1970-01-01
      • 2011-09-22
      • 1970-01-01
      相关资源
      最近更新 更多