[英]Python oop Pass an object as the argument and use its method inside the method of another object
I want to pass an object of the class as the argument in one of the methods of the same class. 我想在同一类的方法之一中将类的对象作为参数传递。
There are some answers on Stack Overflow, but they embrace very simple examples without methods. 关于堆栈溢出有一些答案,但是它们包含非常简单的示例,没有方法。 Yes, I know, that passing an object is not different from passing an integer.
是的,我知道,传递对象与传递整数没有什么不同。 The problem is that when I pass it as an argument in the same way as integer I have an error when I am calling the method of the class.
问题是,当我以与整数相同的方式将其作为参数传递时,在调用类的方法时会出错。
Here is my example. 这是我的例子。
The object of my class is a point. 我班的目的是重点。 It has two attributes, which are x, y coordinates.
它具有两个属性,分别是x,y坐标。 I want to have a method, which will calculate a distance from the object to another object passed.
我想要一个方法,该方法将计算从对象到另一个传递的对象的距离。 I use getters to get the values of the attributes.
我使用吸气剂来获取属性的值。
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
The error appears in the last line. 错误出现在最后一行。
line 34, in Distance
return math.sqrt(((self._x - m_object.X) ** 2) + (self._y - m_object.Y ** 2))
ValueError: math domain error
So how to pass an object 1 as an argument to another object 2, so that I could use the methods object 1 in the method of the object 2? 那么如何将对象1作为参数传递给另一个对象2,以便可以在对象2的方法中使用对象1的方法?
return math.sqrt(((self._x - m_object.X) ** 2) + (self._y - m_object.Y ** 2))
Should be: 应该:
return math.sqrt(((self._x - m_object.X) ** 2) + ((self._y - m_object.Y) ** 2))
You forgot parentheses around Y difference. 您忘记了Y差周围的括号。
the issue is with math.sqrt function . 问题是math.sqrt函数。 it does not accept negative numbers.
它不接受负数。
return math.sqrt(((self._x - m_object.X) ** 2) + ((self._y - m_object.Y) ** 2))
is the correct way. 是正确的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.