Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/316.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
应用@staticmethod,python3_Python_Static Methods - Fatal编程技术网

应用@staticmethod,python3

应用@staticmethod,python3,python,static-methods,Python,Static Methods,我打算制作一个新用户生成的函数,只向用户返回一个名称,还没有列表,因此名称槽中有x 我的问题:这是@staticmethod的正确用法,还是我遗漏了它的全部要点 据我所知,在这种情况下,它允许用户使用userinput.create_new_user('tim'),而不必预先定义类,tim=userinput(“foo”,,,,,,,);它在现场创建它 我试图将函数创建新用户转换为: @staticmethod def create_new_user(): 打印(“要创建多少用户”) x=int

我打算制作一个新用户生成的函数,只向用户返回一个名称,还没有列表,因此名称槽中有x

我的问题:这是
@staticmethod
的正确用法,还是我遗漏了它的全部要点

据我所知,在这种情况下,它允许用户使用userinput.create_new_user('tim'),而不必预先定义类,tim=userinput(“foo”,,,,,,,);它在现场创建它

我试图将函数
创建新用户
转换为:
@staticmethod
def create_new_user():
打印(“要创建多少用户”)
x=int(输入())
y=0
当y
在静态方法中,您不能使用类变量,您的代码应该

@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
编辑:


使用
userinput.users.append

在静态方法中,如果不能使用类变量,代码应该

@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
编辑:


使用
userinput.users.append
使用
@classmethod
将是最简单的选择

NameError: global name 'users' is not defined
@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)
如果我们在使用新类时将
UserInput
子类化,它也可以工作

但是请注意,
x=cls(“x”,“x”,“x”,“x”,“x”)
并不是很有用;最好

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.
我现在可以这样使用它:

    @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
但是我想知道这个类是否真的是存储新用户的正确位置,并且只存储那些使用这个函数创建的用户。也许最好直接在
\uuuu init\uuuu
中输入
用户
列表,并让此函数处于更高的级别


这里使用
@classmethod
的优点是,您总是在正确的基础上工作

假设您有一个
UserInput
,上面有一个
\uuuu init\uuuu()
方法。然后您可以将其子类化并执行以下操作

UserInput.create_new_users()
使用@classmethod将是最简单的选择

NameError: global name 'users' is not defined
@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)

现在,您可以让您的
在基类中创建新的用户()
,并成为
@classmethod
,它将根据您如何调用它来选择正确的
\uuuuu init\uuuuuuuuuuu

使用
@classmethod
将是最简单的选择

NameError: global name 'users' is not defined
@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)
如果我们在使用新类时将
UserInput
子类化,它也可以工作

但是请注意,
x=cls(“x”,“x”,“x”,“x”,“x”)
并不是很有用;最好

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.
我现在可以这样使用它:

    @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
但是我想知道这个类是否真的是存储新用户的正确位置,并且只存储那些使用这个函数创建的用户。也许最好直接在
\uuuu init\uuuu
中输入
用户
列表,并让此函数处于更高的级别


这里使用
@classmethod
的优点是,您总是在正确的基础上工作

假设您有一个
UserInput
,上面有一个
\uuuu init\uuuu()
方法。然后您可以将其子类化并执行以下操作

UserInput.create_new_users()
使用@classmethod将是最简单的选择

NameError: global name 'users' is not defined
@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)


现在您可以让您的
创建新用户()
在基类中,并且是一个
@classmethod
,它将根据您对它的调用方式选择正确的
\uuuu init\uuuuu
进行调用。

请更正缩进。这里还有语法错误,对不起,我忘了everytime@qwwqwwq现在我修复了缩进和一些明显的语法,append(x)对于users.append(x),它的工作方式是
tim=userinput(“foo”,“”,“”,“”,“”,“”,“”,“”)不创建类,而是创建它的实例。只要执行
类…:
正文,就会创建该类。请更正缩进。此处还有语法错误。对不起,我忘记了everytime@qwwqwwq现在,我修复了缩进和一些明显的语法,append(x)to nothing changed to users.append(x),它正在工作
tim=userinput(“foo”、“”、“”、“”、“”、“”)不创建类,而是创建它的实例。只要执行
类…:
主体,就会创建该类。对,但这是一个怎样的答案?是的,确实如此,那么在这种情况下最好使用class方法
@staticmethod
不能允许引用任何类变量。这意味着id必须已经创建了一个全局列表,我的函数才能工作;如果将
@staticmethod
及其下的函数转换为
@classmethod
,是否会更有益?这是正确的用法,我只需要参考类中的列表。Thanks@TimLayne我肯定会在这里使用
@classmethod
。@glglglgl为什么你认为
@classmethod
在这种情况下会更好?如果我使用
@classmethod
,我必须先创建类,然后才能使用