CMinusMinus
CMinusMinus

Reputation: 456

Nested classes in object oriented python

I would like to do the following:

import mymodule

m = mymodule.MyModule()

m.dosth()
# Does something

m.more.domore()
# Does more

The mymodule __init__.py file looks like this:

class MyModule():
    def __init__(self):
        pass # Constructor

    def dosth(self):
        print("My module is doing something!")
    
    class more:
        def domore(self):
            print("My module is doing even more!")

But when I run my script, a TypeError occurres: TypeError: domore() missing 1 required positional argument: 'self. How can I call methods from the class more without getting errors?

Upvotes: 0

Views: 112

Answers (2)

Yevhen Kuzmovych
Yevhen Kuzmovych

Reputation: 12130

This method either needs to be static:

class MyModule():
    def __init__(self):
        pass # Constructor
    def dosth(self):
        print("My module is doing something!")

    class more:
        @staticmethod
        def domore():
            print("My module is doing even more!")

with

m = MyModule()
m.more.domore()
# or directly
MyModule.more.domore()

or you need to create an instance of more first:

m = MyModule.more()
m.domore()

Upvotes: 3

Drethax
Drethax

Reputation: 75

Adding () after more solved the problem for me

m.more().domore()

Upvotes: 2

Related Questions