Question

My code needs to have an inner class and I want to create the instance of this inner class without creating the instance of outer class.
How to do so in python? In java we can define the inner class to be static but I don't know how to make a inner class static in python. I know that for methods we can use @staticmethod decorator.

class Outer:
    def __init__(self):
        print 'Instance of outer class is created'

    class Inner:
        def __init__(self):
            print 'Instance of Inner class is created'
Était-ce utile?

La solution

The class Inner is defined during the definition of the class Outer and it exists in its class namespace afterwards. So just Outer.Inner().

Autres conseils

You don't need to do anything special. Just refer to it directly:

instance = Outer.Inner()

Not sure this is what you looking for. You can just create it as class variable or as global (module) variable

class Outer:
    def __init__(self):
        print 'Instance of outer class is created'

    class Inner:
        def __init__(self):
            print 'Instance of Inner class is created'

    i = Inner() # as class varaible

i1 = Outer.Inner() # as module varaible
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top