【问题标题】:Class variable vs reference to parent in python类变量与python中对父级的引用
【发布时间】: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


【解决方案1】:

我认为集成这些类没有任何问题。您唯一会失去的东西(据我所知)是批量生成具有相同image 的实例,以及具有相同image 的所有实例的列表。为此,我推荐一个函数:

profile_lines = []
def generate_profile_lines (image, lines): 
    # image will be whatever it was before, line will be a list since you (seem to) want to have multiple instances with different lines and the same image
    global profile_lines
    profile_lines.append ([Profile_Line (image, line) for line in lines])

您可能已经注意到,我将image 传递给Profile_Line。这是因为我认为您应该对其进行重组以接受image 作为参数。

【讨论】:

  • 这样,全球profile_lines的每个子列表都会有自己的形象——有点像你的经理。
  • 我明白了,但是如果图像发生变化,我将不得不为每个 profile_line 更改它。反过来整合,让经理自己处理线路怎么样。这意味着将函数“get_results”放入管理器并让他循环遍历行?
  • 经理类的变量“图像”可以直接从外部更改,因为它没有标记为私有“_”。
  • 你想让我做一个函数来做到这一点吗?
  • 不,没必要,谢谢!我只是从结构的角度寻找最佳解决方案。
猜你喜欢
  • 1970-01-01
  • 2019-04-10
  • 1970-01-01
  • 1970-01-01
  • 2017-04-11
  • 1970-01-01
  • 2013-03-29
  • 2015-02-03
相关资源
最近更新 更多