Defining a class within another class and calling a parent method

梦想与她 提交于 2019-12-07 16:37:53

问题


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()

回答1:


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.



来源:https://stackoverflow.com/questions/8878344/defining-a-class-within-another-class-and-calling-a-parent-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!