【问题标题】:How to call class method from dict declared inside Class?如何从类中声明的dict调用类方法?
【发布时间】:2020-08-06 14:00:15
【问题描述】:

我正在尝试在一个类中创建一个 dict,其中键作为提示命令,类方法作为值,但是在尝试运行模块时我遇到了以下问题

cmd = {'-v': self.view_leagues(), NameError: name 'self' is not defined

我不明白为什么我不能这样做?

示例代码如下:

class CLIStats:

    cmd = {'-v': self.view_leagues(),
           'exit': 'sys.exit()',
           'Back To Home': '-b',
           'View Stats Type': '-s',
           'Help' : '-h' }

    def __init__(self):
        self.leagues = {'EN_PR': ['2019/2020', '2018/2019']}

    def view_leagues(self):
        for league in self.leagues.keys():
            print("{: <10}".format(league), end="")
        print('\n')


def main():
    interface = CLIStats()
    print(interface.cmd.keys())


if __name__ == '__main__':
    main()

【问题讨论】:

    标签: python oop


    【解决方案1】:

    您只需要在__init__() 中声明变量。试试这个:

    class CLIStats:
        def __init__(self):
            self.leagues = {'EN_PR': ['2019/2020', '2018/2019']}
            self.cmd = {'-v': self.view_leagues(),
                   'exit': 'sys.exit()',
                   'Back To Home': '-b',
                   'View Stats Type': '-s',
                   'Help' : '-h' }
    
        def view_leagues(self):
            for league in self.leagues.keys():
                print("{: <10}".format(league), end="")
            print('\n')
    
    
    def main():
        interface = CLIStats()
        print(interface.cmd.keys())
    
    
    if __name__ == '__main__':
        main()
    

    如果您想创建 cmd 广告独立变量,请使用以下代码:

    class CLIStats:
        def __init__(self):
            self.leagues = {'EN_PR': ['2019/2020', '2018/2019']}
    
        def view_leagues(self):
            for league in self.leagues.keys():
                print("{: <10}".format(league), end="")
            print('\n')
    
    
    def main():
        interface = CLIStats()
        cmd = {'-v': interface.view_leagues(),
               'exit': 'sys.exit()',
               'Back To Home': '-b',
               'View Stats Type': '-s',
               'Help' : '-h' }
        print(cmd.keys())
    
    
    if __name__ == '__main__':
        main()
    

    【讨论】:

    • 我明白了,谢谢您的输入!如果我可能会问,为什么必须在 __init__ 方法中声明 cmd 并且不能不是独立变量?
    • 因为您使用的是类内部的函数,并且您需要将self 添加到cmd,因为您正在使用类的实例在print(interface.cmd.keys()) 中访问..
    • 我明白了!因为问题是在__init__()中声明cmd时,在执行模块时会调用self.view_leagues(),但我希望在命令上执行该方法。
    • 谢谢你,为什么我不能做我想做的事是有道理的!
    • 我已经在上面进行了测试,但它没有按预期工作,cmd 中的函数在 cmd 被声明时被执行。但是 cmd 中的值只有在用户提示该特定值的键时才应该执行
    猜你喜欢
    • 1970-01-01
    • 2015-07-10
    • 2021-03-09
    • 1970-01-01
    • 2020-12-10
    • 2018-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多