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
CMinusMinus
4561 gold badge3 silver badges11 bronze badges
-
Why? Nested classes are rare in Python, as are static methods (though less so).chepner– chepner2020年07月15日 12:25:26 +00:00Commented Jul 15, 2020 at 12:25
2 Answers 2
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
Yevhen Kuzmovych
12.3k8 gold badges32 silver badges54 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Tristan Nemoz
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).chepner
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.Adding () after more solved the problem for me
m.more().domore()
Comments
lang-py