Defining a class within another class and calling

2019-05-11 13:52发布

问题:

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.