【问题标题】:Can you call a method on a class and on an instance of the class?你能在类和类的实例上调用方法吗?
【发布时间】:2015-12-18 22:01:05
【问题描述】:

我正在尝试制作一个 Vector 类,它需要三个参数 (x,y,z) 来制作一个矢量对象

u=Vector(3,-6,2) #Creates a vector you with components <3,-6,2>

您可以使用向量做的一件事是添加它们。我正在寻找一种方法来做这样的事情:

u=Vector(3,-6,2)
v=Vector(4,5,-1)
c=Vector.add(u,v) #returns a third vector, the sum of u and v (c = <7,-1,1>)
u.add(v) #modifies u to be the sum of u and v (u = <7,-1,1>)

【问题讨论】:

  • 你应该重写__add__方法。
  • 回答您的确切问题 - Vector.add(u,v)u.add(v) 相同 - add 函数中的 Python 无法区分它们(除非您使用第三个参数或其他方法)。

标签: python object vector methods


【解决方案1】:

你不能同时定义同名的类和实例方法。

但是,我不会创建实例方法.add(),而是重写__add__ 魔术函数,该函数在通过+ 符号添加两个实例时调用。当 Python 尝试评估 x + y 时,它会尝试调用 x.__add__(y)

class Vector(object):
    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z

    def __repr__(self):
        return '<Vector: {}, {}, {}>'.format(self.x, self.y, self.z)

    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y, self.z + other.z)

    @classmethod
    def add(cls, v1, v2):
        return cls(v1.x + v2.x, v1.y + v2.y, v1.z + v2.z)

--

>>> u = Vector(1, 2, 3)
>>> v = Vector(4, 5, 6)
>>> c = u + v
>>> print c
<Vector: 5, 7, 9>

>>> c = Vector.add(u, v)
>>> print c
<Vector: 5, 7, 9>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-05
    • 2015-06-19
    • 2014-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多