类变量与python中对父类的引用

问题描述 投票:0回答:1

我有一个风格问题。使用“管理器对象”的引用来管理对象之间的共享变量是一个坏主意吗?

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对象都具有相同的图像,即使它们不属于一起。

将父对象传递给属于该管理器的配置文件行对象是一个好主意吗?感觉有点奇怪。或者有更好的方法来做到这一点,例如将两个类集成为一个。

python class variables reference parent
1个回答
0
投票

我没有看到集成类的任何问题。你唯一丢失的东西(据我所知)是批量生成具有相同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作为参数。

© www.soinside.com 2019 - 2024. All rights reserved.