使用@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 的好处是您始终在正确的基础上工作。
假设你有一个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__ 进行调用。