【问题标题】:What's wrong with the use of these classes?使用这些类有什么问题?
【发布时间】:2018-03-08 12:55:24
【问题描述】:

我正在尝试调用函数 login() 但是您可以看到它没有定义,这意味着我完全错误地理解了类 - 我试图理解那里的用途正如你所见,我什至不是初学者。

Screenshot of code in emulator

感谢任何帮助或提示!

【问题讨论】:

  • 请不要将您的代码/错误作为图像。使用代码格式将它们写在您的问题中(缩进 4 个空格)
  • self.login(),但使用这样的类没有意义。只需定义一些函数。

标签: python python-3.x function class


【解决方案1】:

我认为您正在尝试编写此类:

class Menu_choice():
    def login(self):
        print("Login")
    def register(self):
        pring("Register")
    def __init__(self, choice):
        self.choice = choice
        if self.choice == "LOGIN":
            self.login()
        if self.choice == "REGISTER":
            self.register()

但正如其他人指出的那样,这个类本身没有任何意义。我想你想要这样的东西:

class Menu_choice():
    def __init__(self):
        pass
    def login(self):
        print("Login")
    def register(self):
        print("Register")
    def __call__(self, choice):
        self.choice = choice
        if self.choice == "LOGIN":
            self.login()
        if self.choice == "REGISTER":
            self.register()

choice = input("Would you like to login or register?: ").upper()
m = Menu_choice()
m(choice)

您可以将您的类实例化为m,还可以定义一个__call__() 函数,该函数将在您调用m(choice) 之类的实例时执行

【讨论】:

  • 请原谅我的无能,感谢您的解决方案!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-11-16
  • 1970-01-01
  • 1970-01-01
  • 2013-11-06
  • 2016-07-29
  • 1970-01-01
相关资源
最近更新 更多