使用@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", "", "", "", "")并不是很有用;最好这样做
^{pr2}$
我现在可以这样使用它: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)
但是我想知道这个类是否真的是存储新用户的正确位置,而且只存储那些用这个函数创建的用户。也许最好直接在__init__中提供users列表,并让这个函数处于更高的级别。在
在这里使用@classmethod的好处是你总是在正确的基础上工作。在
假设您有一个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__进行调用。在