创建一个parent.child类结构,其中的孩子有一个
问题描述:
我有下面的代码发生问题,因为子对象需要参数,才可以创建一个实例。我是否需要创建某种函数来处理创建子对象?创建一个parent.child类结构,其中的孩子有一个
我希望能够做到:
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)
包含与每个配置文件相关的任务/例程。然后,我想parent.profile(profile_id).extract(extract_id)
包含与每个摘录相关的任务/例程。
答
当您询问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