【发布时间】:2018-02-28 15:30:31
【问题描述】:
我有一个风格问题。 使用“管理器对象”的引用来管理对象之间的共享变量是不是一个坏主意?
class Profile_Line:
def __init__(self, parent, line):
self.parent = parent
self.line = line
def get_results(self):
image = self.parent.image # Is this a good idea?
profile_line = self.get_profile_line(image, self.line)
return profile_line
def get_profile_line(self,img,line):
return [1,2,3,4] #not real function
class Profile_Line_Manager():
def __init__(self, image):
self.image = image
self.p_lines = [] # a list of Profile Line objects
def add_profile_line(self, line):
self.p_lines.append(Profile_Line(self, line))
def get_results(self):
for pl in self.p_lines:
print(pl.get_results())
所以有一个类 Profile Line,它使用自己的参数以及通过管理器获取的图像计算一些值。 属于同一经理的所有配置文件行的图像都是相同的。 所以不能使用类变量,因为所有 profile_line 对象都会有相同的图像,即使它们不属于一起。
将父对象传递给属于该经理的轮廓线对象是个好主意吗?感觉有点奇怪。 或者有没有更好的方法来做到这一点,例如将两个类合二为一。
【问题讨论】:
-
第一个
def get_results在某种程度上被严重破坏了。要么缩进不正确,和/或不清楚它的parent来自哪里。 -
谢谢,父项被指定为实例变量“self.parent”。函数 get_profile_line 还不存在,但我们假设它只是返回一些整数列表。
-
仍然不正确的缩进和缺少
self...!? -
是的,但我无法编辑它,因为提交的编辑太少了。可以试试吗?
-
哦,我的错,现在好点了吗? :)
标签: python class variables reference parent