在另一个类中定义一个类并调用父方法
我有 C 类定义和该类的一些内部类定义:
class DoXJob():
def __init__(self, param1, param2):
<choose an inner class to use>
def DoIt(self):
pass
def Finalize(self):
<do finalization>
class DoXInSomeWay():
def __init__(self):
....
....
def DoIt(self):
...
class DoXInSomeOtherWay():
def __init__(self):
....
....
def DoIt(self):
...
逻辑很简单,我有一些内部类定义来处理作业,我用一些参数调用 DoXJob,然后它决定哪个内部类将被使用,并使用选定的内部类方法(DoXInSomeOtherWay.DoIt
或DoXInWay.DoIt
)的方法覆盖DoXJob.DoIt
obj = DoXJob(param1, param2)
obj.DoIt()
方法很好,我想要的是从 ineer 类触发 DoXJob.Finalize
,就像从 DoXInSomeOtherWay.DoIt
或 DoXInWay.DoIt
调用它。但我不知道如何处理这个问题,也不知道这是否是正确的方法。或者最好将其作为 DoXJob
方法调用,例如:
obj = DoXJob(param1, param2)
obj.DoIt()
obj.Finalize()
I have c class definition and some inner class definitions for that class:
class DoXJob():
def __init__(self, param1, param2):
<choose an inner class to use>
def DoIt(self):
pass
def Finalize(self):
<do finalization>
class DoXInSomeWay():
def __init__(self):
....
....
def DoIt(self):
...
class DoXInSomeOtherWay():
def __init__(self):
....
....
def DoIt(self):
...
Logic is simple, i have some inner class definitions to handle a job, and i call DoXJob
with some parameters, it then decides which inner class will be used, and override DoXJob.DoIt
method with the method of selected inner class method (DoXInSomeOtherWay.DoIt
or DoXInWay.DoIt
)
obj = DoXJob(param1, param2)
obj.DoIt()
All is fine, what i want is to trigger DoXJob.Finalize
from the ineer classes, like calling it from the DoXInSomeOtherWay.DoIt
or DoXInWay.DoIt
. But i do not know how to handle this, and whether is it the right way. Or is it better to make as a DoXJob
method call like:
obj = DoXJob(param1, param2)
obj.DoIt()
obj.Finalize()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不幸的是,python 似乎没有办法引用封闭的实例。
相反,在您选择要使用哪个内部类并可能实例化它的外部
__init__
中,您需要将外部对象的self
作为参数传递给内部类实例。编辑:选择重新设计的主题 - 如果您可以简单地调用
DoIt
方法,然后等待它的返回,那么您可以在同一位置调用Finalize
(调用者,即),从而避免了内部调用外部的需要。Unfortunately, python doesn't seem to have a way to refer to the enclosing instance.
Instead, in your outer
__init__
where you choose which inner class to use, and presumably instantiate it, you will need to pass the outer object'sself
as a parameter to the inner class instance.Edit: Picking up the theme of a redesign - if you can simply call the
DoIt
method, then wait for its return, then you can callFinalize
in the same place (the caller, that is), thus avoiding the need for the inner to call the outer.