简体   繁体   中英

How to call class method from dict declared inside Class?

I'm trying to create a dict within a class with keys as prompt-commands and class methods as values, but I'm getting below when trying to run the module

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

I do not understand why I'm not able to do this?

Example code below:

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()

You just need declare the variables inside __init__() . Try this:

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()

If you want to create cmd ad standalone variable use the following code:

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM