Abhishek Gupta
Abhishek Gupta

Reputation: 6615

Static inner class in python

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'

Upvotes: 13

Views: 10254

Answers (3)

Adam Bartoš
Adam Bartoš

Reputation: 717

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

Upvotes: 13

Martijn Pieters
Martijn Pieters

Reputation: 1124188

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

instance = Outer.Inner()

Upvotes: 1

eran
eran

Reputation: 6921

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

Upvotes: 0

Related Questions