在另一个类中定义一个类并调用父方法 [英] Defining a class within another class and calling a parent method

查看:161
本文介绍了在另一个类中定义一个类并调用父方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有c类定义和该类的一些内部类定义:

  class DoXJob():
def __init __(self,param1,param2):
<选择一个内部类使用>

def DoIt(self):
pass

def完成(self):
< do finalization>

class DoXInSomeWay():
def __init __(self):
....
....
def DoIt(self):
...

class DoXInSomeOtherWay():
def __init __(self):
....
....
def DoIt(self):
...

逻辑很简单,定义来处理一个作业,我调用 DoXJob 一些参数,然后决定使用哪个内部类,并覆盖 DoXJob.DoIt 方法与选定的内部类方法( DoXInSomeOtherWay.DoIt DoXInWay.DoIt ) / p>

  obj = DoXJob(param1,param2)
obj.DoIt()

一切都很好,我想要的是从ineer类中触发 DoXJob.Finalize 例如从 DoXInSomeOtherWay.DoIt DoXInWay.DoIt 调用它。但我不知道如何处理这一点,是否是正确的方法。或者最好是作为 DoXJob 方法调用:

  obj = DoXJob(param1,param2)
obj.DoIt()
obj.Finalize()




相反,在你的外部 __ init __ 中你选择使用哪个内部类,并假设它实例化,你将需要传递外部对象的 self 作为内部类实例的参数。



编辑:拾取重新设计的主题 - 如果你可以简单地调用 DoIt 方法,然后等待其返回,那么您可以在同一位置(调用者)调用 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()

解决方案

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's self 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 call Finalize in the same place (the caller, that is), thus avoiding the need for the inner to call the outer.

这篇关于在另一个类中定义一个类并调用父方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆