class UserInput():
users=[]
def __init__(self, name,lista,listb,listc,listd):
self.name=""
self.lista=lista
self.listb=listb
self.listc=listc
self.listd=listd
@staticmethod
def create_new_user(x):
x=userinput("x","","","","")
users.append(x)
我打算创建一个生成新用户的函数,只向用户返回一个名称,但还没有列表,因此名称槽中包含 x。
我的问题:这是 @staticmethod
的正确用法还是我错过了它的全部要点?
据我了解,在本例中,它允许用户使用userinput.create_new_user('tim')
,而无需预先定义类,tim=userinput("foo", "","","","");它当场创建。
我试图将函数 create_new_users
转换为:
@staticmethod
def create_new_user():
print("how many users do you want to create")
x=int(input())
y=0
while y < x:
print("assign the users names")
name = input("")
if name == "" or "None,none":
raise SyntaxError("name cannot be None or empty")
break
name=userinput("","","","","")
userinput.users.append(name)
y+=1
最佳答案
在静态方法中你不能使用类变量,你的代码应该得到
NameError: global name 'users' is not defined
编辑:
使用userinput.users.append
关于python - 应用@staticmethod,python3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20917252/