Beorn
Beorn

Reputation: 437

Declaring inner class out of the class

I want to use inner class in my code but I have problem with planning how should it looks like, maybe even it's bad use of it so you could help me to find other way to write it. I wish this inner class would have been created in some if structure, depending on the string provided in input. It would be nice if I could write the code of this inner class outside it's parent class because it might be huge in the future and it should be easy to extend.

I was wondering if I should just use inheritage like Case1(Case1), but im not sure about this.

class Example:
    def declare_specific_case(self):
        if "case1" in foo:

            class Case1:
                pass

        elif "case2" in foo:

             class Case2:
                 pass
    
class Case1:
    <some code which can be used in inner class>

So I expect that I can declare the code outside the class maybe even in other module.

Upvotes: 0

Views: 34

Answers (1)

Raydel Miranda
Raydel Miranda

Reputation: 14360

You can do something like this:

class Class1: pass
class Class2: pass

class Wrapper:
   def __init__(self, x):
       if x:
           self._inner = Class1
       else:
           self._inner = Class2

even you can add a convenience method just like:

class Wrapper:
    # ...
    def get_inner_class_instance(self, *args, **kwargs):
        return self._inner(*args, **kwargs)

On the other hand, perhaps you want to look on how to implement the Factory Pattern using python. Take a look to this article: https://hub.packtpub.com/python-design-patterns-depth-factory-pattern/

Upvotes: 2

Related Questions