【问题标题】:Creating a parent.child class structure where the child has a创建一个 parent.child 类结构,其中孩子有一个
【发布时间】:2014-12-03 07:50:05
【问题描述】:

我有以下代码出现问题,因为子对象在创建实例之前需要参数。我是否需要创建某种函数来处理子对象的创建?

我希望能够做到:

a = parent()
a.other('param').double(2)
2
a.other('param').other_class('another_param').square(4)
16

这是我的代码:

class parent(object):

    def __init__(self):
        self.other = other_class2(self)
        self.answer = None

    def multiply(self,x,y):
        self.answer = x*y
        return x*y

    def add(self,x,y):
        self.answer = x+y
        return x+y


class other_class(object):

    def __init__(self,parent,inputed_param):
        self.parent = parent
        self.input = inputed_param

    def square(self,x):
        self.answer = self.parent.parent.multiply(x,x)
        return self.parent.parent.multiply(x,x)


class other_class2(object):

    def __init__(self,parent,inputed_param):
        self.parent = parent
        self.other_class = other_class(self)
        self.input = inputed_param

    def double(self,x):
        self.answer = self.parent.add(x,x)
        return self.parent.add(x,x)

在我的实际代码中,我正在创建一个 python 包装器来自动化创建 profiles 的网站中的任务,每个 profile 中都有许多 extracts强>。我认为这种树状结构将是管理所有相关例程的最佳方式。

我需要一个父类来维护与网站的连接,我希望parent.profile(profile_id) 包含与每个配置文件相关的任务/例程。然后,我希望 parent.profile(profile_id).extract(extract_id) 包含与每个 extract 相关的任务/例程。

【问题讨论】:

    标签: python class parent-child class-structure


    【解决方案1】:

    当您询问param 时,您可以构建课程。该代码应该实现您想要的行为。

    class parent(object):
    
        def __init__(self):
            self.other = lambda param: other_class2(self,param)
            self.answer = None
    
    class other_class2(object):
    
        def __init__(self,parent,inputed_param):
            self.parent = parent
            self.other_class = lambda param: other_class(self,param)
            self.input = inputed_param
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-16
      • 2018-11-08
      • 1970-01-01
      • 2011-10-05
      • 2018-07-23
      • 2021-12-15
      • 2021-06-01
      • 1970-01-01
      相关资源
      最近更新 更多