我有以下代码出现问题,因为子对象在创建实例之前需要参数。我是否需要创建某种函数来处理子对象的创建?
我希望能够做到:
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 包装器来自动化创建配置文件的网站中的任务,每个配置文件中都有一些提取。我认为这种树结构将是管理所有相关例程的最佳方式。
我需要一个父类来维护与网站的连接方面,并且我想包含与每个配置文件parent.profile(profile_id)
相关的任务/例程。然后,我想包含与每个extract相关的任务/例程。parent.profile(profile_id).extract(extract_id)