【发布时间】: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