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”,“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
最佳答案
使用@classmethod
将是最简单的选择。
class UserInput: # capitals! Look at PEP 8.
users = [] # rearranged to the top for better readability
def __init__(self, name, lista, listb, listc, listd):
self.name = ""
self.lista = lista
self.listb = listb
self.listc = listc
self.listd = listd
@classmethod
def create_new_user(cls): # no need for x if you overwrite it immediately
x = cls("x", "", "", "", "")
cls.users.append(x) # easier access to this static attribute
return x # for the caller having access to it as well.
如果我们在使用新类时对
UserInput
进行子类划分,那么它也可以工作。但是请注意,
x = cls("x", "", "", "", "")
并不是很有用;最好是 @classmethod
def create_new_user(cls, *a, **k): # no need for x if you overwrite it immediately
x = cls(*a, **k) # pass the arguments given by the caller to __init__.
cls.users.append(x) # easier access to this static attribute
return x # for the caller having access to it as well.
我现在可以这样用了:
a = UserInput("foo", "whatever", "is", "needed", "here")
或者,如果我选择,
a = UserInput.create_new_user("foo", "whatever", "is", "needed", "here")
它还将新用户附加到列表中。
如果要缩短参数列表,也可以这样做:
def __init__(self, name, lista=None, listb=None, listc=None, listd=None):
self.name = name
self.lista = lista if lista is not None else []
self.listb = listb if listb is not None else []
self.listc = listc if listc is not None else []
self.listd = listd if listd is not None else []
如果他们真的是名单。如果它们是字符串,则可以使用另一个名称,因为字符串是不可变的,所以您可以简单地
def __init__(self, name, lista='', listb='', listc='', listd=''):
self.name = name
self.lista = lista
self.listb = listb
self.listc = listc
self.listd = listd
把这些东西和
a = UserInput.create_new_user("foo", listc=...) # all others are left empty
b = UserInput("bar") # all are left empty
c = UserInput.create_new_user("ham", lista=..., listd=...) # all others are left empty
既然你提出了一个不同的任务,我也会努力解决:
@classmethod
def create_new_users(cls): # several users!
print("how many users do you want to create")
num = int(input())
for _ in range(num): # simpler iteration
print("enter the user's name")
name = input("") # in 3.x, this is always a string, so it cannot be None...
# if name == "" or "None,none": # That won't work as you think.
if name == '' or name.lower() == 'none': # but why disallow the string 'None'?
# raise SyntaxError("name cannot be None or empty")
raise RuntimeError("name cannot be None or empty") # or ValueError or alike
# break not needed. raise jumps out without it as well.
user = cls(name, "", "", "", "") # name is an input, not an output.
cls.users.append(name)
但是我想知道这个类是否真的是存储新用户的正确位置,并且只存储那些用这个函数创建的用户。也许最好直接在
users
中输入__init__
列表,让这个函数处于更高的级别。在这里使用
@classmethod
的好处是您总是在corret的基础上工作。假设您有一个
UserInput
和一个__init__()
方法,如上所述。然后你可以将其子类化UserInput.create_new_users()
使用@classmethod将是最简单的替代方法。class UserInputStoring(UserInput):
users = [] # this is only here, not at the parent.
def __init__(self, *a, **k):
super(UserInputStoring, self).__init__(*a, **k) # pass everything up as it was used
self.users.append(self)
现在您可以将
create_new_users()
放在基类中,并成为一个@classmethod
,它将根据您的调用方式选择正确的__init__
来调用。关于python - 应用@ staticmethod,python3,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20917252/