python - 应用@staticmethod,python3

标签 python static-methods

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/

相关文章:

java - 使用无状态 Bean 和 DI 代替 POJO 和静态方法有哪些优点

C++ 如何通过回调方法访问成员变量

c# - c#中私有(private)静态方法有什么用?

c# - 使用静态方法的充分理由?

python - 方法可以用作静态方法还是实例方法?

python - Discord.py task.loop 用于更改齿轮不工作的状态

python - 导入错误 : No module named win32api while using Scrapy

python - 3个嵌套循环: Optimizing a simple simulation for speed

python - 在 python 中先抓取后如何移动到第二页

python - Selenium 网络驱动程序 : how do respond on a prompt