【问题标题】:Subtle unexpected behaviour with a function used as class-attribute用作类属性的函数的微妙意外行为
【发布时间】:2014-03-20 08:19:25
【问题描述】:

当我更改属性并将其设为类属性时,我有一段代码被破坏,我很想了解原因。

所以,我开始了

def linInterp(x1, x2, y1, y2, x):
    return y1 + (x - x1) * (y2 - y1) / (x2 - x1)

class Inter1DLineal(object):
    def __init__(self):
        self.interpSegment = linInterp

if __name__ == "__main__":
    inter = Inter1DLineal()
    print(inter.interpSegment(0.2, 0.6, 0, 1, 0.4))

没问题。我知道我可以将interpSegment 实现为Inter1DLineal 中的正确方法,例如

@classmethod
def interpSegment(cls, *args, **kwargs):
    return linInterp(*args, **kwargs)

但我认为我对函数类型的属性很好。

让我惊讶的是接下来发生的事情。我决定,因为interpSegment 对所有实例都是通用的,所以我应该将其设为类属性。

def linInterp(x1, x2, y1, y2, x):
    return y1 + (x - x1) * (y2 - y1) / (x2 - x1)

class Inter1DLineal(object):
    interpSegment = linInterp
    def __init__(self):
        pass

if __name__ == "__main__":
    inter = Inter1DLineal()
    print(inter.interpSegment(0.2, 0.6, 0, 1, 0.4))

但这破坏了代码。似乎对 interpSegment 的调用现在传递了 6 个属性,而不是 5 个。有人可以解释为什么会发生这种情况吗?这样做最 Python 的方式是什么?

【问题讨论】:

标签: python class-attributes


【解决方案1】:

您将inter 作为第一个参数传递,即self 参数。所以本质上,在"__main__" 代码中,您传递的内容如下:

interpSegment(inter, 0.2, 0.6, 0, 1, 0.4)

你应该把它称为:

Inter1DLineal.interpSegment(0.2, 0.6, 0, 1, 0.4)

但是,我还要声明,您首先在 interpSegment 中的 __init__ 中执行的操作或作为单独的方法是一种更好的方法。

【讨论】:

  • 感谢您的回答。你当然是对的。但是仍然有点令人费解的是为什么相同的调用在一种情况下有效,而在另一种情况下无效。希望当我阅读 Janne 建议的帖子时,我会更好地理解。无论如何,我会去实现 interpSegment 作为一种方法。
  • 没问题。很高兴我能帮上忙
猜你喜欢
  • 2018-11-29
  • 1970-01-01
  • 1970-01-01
  • 2021-04-09
  • 1970-01-01
  • 2019-08-28
  • 2021-02-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多