【问题标题】:Python oop Pass an object as the argument and use its method inside the method of another objectPython oop 传递一个对象作为参数,并在另一个对象的方法中使用它的方法
【发布时间】:2018-03-11 16:46:52
【问题描述】:

我想将类的对象作为参数传递给同一类的方法之一。

Stack Overflow 上有一些答案,但它们包含没有方法的非常简单的示例。是的,我知道,传递一个对象与传递一个整数没有什么不同。问题是当我以与整数相同的方式将它作为参数传递时,当我调用类的方法时出现错误。

这是我的例子。

我班级的对象是一个点。它有两个属性,分别是x,y坐标。我想要一个方法,它将计算从对象到传递的另一个对象的距离。我使用 getter 来获取属性的值。

import math

class Point:
    """Point class, whose object is a point"""

    def __init__(self, m_x=0, m_y=0):
        self._x = m_x
        self._y = m_y

    @property
    def X(self):
        """X coordinate"""
        return self._x

    @X.setter
    def X(self, m_x):
        self._x = m_x

    @property
    def Y(self):
        """Y coordinate"""
        return self._y

    @Y.setter
    def Y(self, m_y):
        self._y = m_y

    def ToString(self):
        """Prints a string with coordinates"""
        print("Point x: {}, y: {}".format(self._x, self._y))

    def DistanceOrigin(self):
        """Calculates a distance to the origin of the coordinate axis (0,0)"""
        return math.sqrt((self._x ** 2) + (self._y ** 2))

    def Distance(self, m_object):
        """Calculates a distance to another object"""
        return math.sqrt(((self._x - m_object.X) ** 2) + (self._y - m_object.Y ** 2))

p = Point(3, 4)

p.ToString()
print(p.DistanceOrigin())

p.X = 2

print(p.X)

q = Point(2, 3)

q.Distance(p) # Here appears the error

错误出现在最后一行。

line 34, in Distance
    return math.sqrt(((self._x - m_object.X) ** 2) + (self._y - m_object.Y ** 2))
ValueError: math domain error

那么如何将一个对象 1 作为参数传递给另一个对象 2,以便我可以在对象 2 的方法中使用方法对象 1?

【问题讨论】:

  • 公式末尾的括号位置错误,应该是+ (self._y - m_object.Y )** 2。这就是为什么您有时会尝试取负数的平方根,这会导致错误。
  • 天哪……是的,这是真的……非常感谢!我应该删除这个帖子吗?
  • 好吧,它可能对其他人没有用......

标签: python python-3.x class oop object


【解决方案1】:
    return math.sqrt(((self._x - m_object.X) ** 2) + (self._y - m_object.Y ** 2))

应该是:

    return math.sqrt(((self._x - m_object.X) ** 2) + ((self._y - m_object.Y) ** 2))

您忘记了 Y 差异周围的括号。

【讨论】:

  • 天哪……是的,这是真的……非常感谢!我应该删除这个帖子吗?
【解决方案2】:

问题在于 math.sqrt 函数。它不接受负数。

    return math.sqrt(((self._x - m_object.X) ** 2) + ((self._y - m_object.Y) ** 2))

是正确的方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 2017-06-02
    • 1970-01-01
    • 2021-12-26
    • 1970-01-01
    • 1970-01-01
    • 2011-03-28
    相关资源
    最近更新 更多