gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 02:28:34 26 4
gpt4 key购买 nike

假设我有一个名为 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com