0

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?

asked Jul 15, 2020 at 12:14
1
  • Why? Nested classes are rare in Python, as are static methods (though less so). Commented Jul 15, 2020 at 12:25

2 Answers 2

3

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()
answered Jul 15, 2020 at 12:16
Sign up to request clarification or add additional context in comments.

2 Comments

I think adding an attribute which is an instance of the more class should also solve the problem, and allows to use m.more the way the OP intends to (from my understanding).
There isn't really enough information about why the OP wants this design to say whether an instance of more should be added as an attribute.
2

Adding () after more solved the problem for me

m.more().domore()
answered Jul 15, 2020 at 12:27

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.