python - 在 Python 中,当一个类使用另一个类时,反之亦然

标签 python class

假设我有一个名为 Point 的类:

class Point:
    def __init__(self, x, y):
        self.__x = x
        self.__y = y
    ...

我还有一个名为 Line 的类,它在内部使用 Point:

class Line:
    #tail and head are supposed to be Point objects
    def __init__(self, tail, head):
        self.__tail = tail
        self.__head = head

问题是我希望 Pointreflect 方法,该方法只是相对于 Line line 反射点:

#Point class
def reflect(self, line):
    #Reflection code that uses Line methods

所以我在这里有交叉引用。问题是解决这个问题的最佳方法是什么?或者我应该避免这种方法?

最佳答案

不,没有交叉引用,没有循环,没有无限循环,也没有无限递归,一切都很清楚。你可以这样做:

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def reflect(self, line):  # line is a Line object
        reflected_x = None # replace w code to calc the reflection of x  vs. line
        reflected_y = None # replace w code to calc the reflection of y  vs. line
        return Point(reflected_x, reflected_y)

class Line:   # a Line defined by two Points 
    def __init__(self, tail, head):
        self.tail = tail
        self.head = head

我删除了变量中的双下划线,一开始就没有理由使用它。

或者:

(following Peter Wood advice in the comments): reflect should probably be a non-member function. It doesn't seem a natural property or behaviour of a Point. You don't want it to be a dumping ground for all your transformations. (hint - maybe create a Transformer object)

或者一个简单的函数,以一条线和一个点作为参数:

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y


class Line:   # a Line defined by two Points 
    def __init__(self, tail, head):
        self.tail = tail
        self.head = head


def reflect(line, point):  # line is a Line object
    reflected_x = None # replace w code to calc the reflection of point.x  vs. line
    reflected_y = None # replace w code to calc the reflection of point.y  vs. line
    return Point(reflected_x, reflected_y)

关于python - 在 Python 中,当一个类使用另一个类时,反之亦然,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47090886/

相关文章:

Python - 正确使用 OR 函数

python - Pandas 无法读取大型 StringIO 对象

c++ - 如何跟踪调用析构函数的位置 - C++

c++ - 让类成员函数调用类外的函数

python - 类型错误 : as_view() - Django

python - 我想计算每个不同组的行数

python - 我应该如何为我的 python 应用程序构建一个简单的数据库包?

c++ - 从派生类添加对象

java - 替换 jar 文件中文件夹内的类文件

javascript - 使用ES6类扩展错误