I have a class interface:
class Interface:
def __init__(self):
self.users_list = []
self.admins_list = []
self.categories_list = []
self.current_user = ''
self.user_flag = 0
@staticmethod
def start_menu(self):
print('Add user')
create_user()
show_menu()
@staticmethod
def create_user(self):
# code....
@staticmethod
def choose_user(self):
# code...
# call
inter = Interface()
inter.start_menu()
And I got the same error:
Traceback (most recent call last):File "C:\Users\79268\Downloads\store.py", line 191, in <module>
inter.start_menu()
TypeError: Interface.start_menu() missing 1 required positional argument: 'self'
I can't figure out what the problem is and the advice from this post (TypeError: Missing 1 required positional argument: 'self') didn't help?
CodePudding user response:
Please read about staticmethod in the documentation.
As you saved the users_list
on the instance, I presume you wish to use those variables in other methods. In this case, you don't need a @staticmethod
.
Refactored start_menu
:
def start_menu(self):
print('Add user')
self.create_user()
self.show_menu()
CodePudding user response:
Static method use only the namespace of the class. It can use class variables but not the ones specific to an object (self
).
If all of them are static methods, then you should change the code as follows because there is no notion of self
in static methods.
class Interface:
users_list = []
admins_list = []
categories_list = []
current_user = ''
user_flag = 0
@staticmethod
def start_menu():
print('Add user')
Interface.create_user()
Interface.show_menu()
@staticmethod
def create_user():
# code....
@staticmethod
def choose_user():
# code...
# call
Interface.start_menu()
If you need self
, make those methods instance methods by removing the staticmethod
decorator. Also, since you have no arguments for the constructor you can make those variables static, like above.
class Interface:
def __init__(self):
self.users_list = []
self.admins_list = []
self.categories_list = []
self.current_user = ''
self.user_flag = 0
def start_menu(self):
print('Add user')
self.create_user()
self.show_menu()
def create_user(self):
# code....
def choose_user(self):
# code...
# call
inter = Interface()
inter.start_menu()
Due to the above-mentioned constraints, an instance method (method referring to the object, i.e., self
) can call static methods but not vice-versa.