0

I'm trying to call functions within a tuple displayed as view(), add(), delete, and exit_program. However, whenever I run the code, the console returns:

TypeError: view() missing 1 required positional argument: 'self'

I also tried to include self or Menu in front of the functions, but to no avail. Is there anyway to fix this?

Here's the code:

from collections import namedtuple

class Menu(object):

    def view(self):
        pass
    def add(self):
        pass
    def delete(self):
        pass
    def exit_program(self):
        exit()

    Option = namedtuple("Option", "label", "function")
    _separator = "=" * 25
    _options = {1: Option('View goals', view()), 2: Option('Add new goal', add()),
                3: Option('Delete existing goal', delete()), 4: Option('Exit program', exit_program())}
  • 1
    `view()` calls the method, in a non-context object – Jean-François Fabre Jul 19 '18 at 22:01
  • 3
    If you're trying to put references to the methods into your option map, you shouldn't be *calling* them. But this whole thing seems a bit convoluted, shouldn't those things belong to an *instance* of the menu rather than the *class*? – jonrsharpe Jul 19 '18 at 22:01
  • Those are class methods and so you need to actually create a class object in order to call them as methods on that object. It should look like `mymenu=Menu()` and then `mymenu.view()` etc. Functions (rather than methods) are not wrapped in a class. – enumaris Jul 19 '18 at 22:01
  • 2
    @enumaris They're defined as instance methods, not class methods. See https://stackoverflow.com/questions/17134653/difference-between-class-and-instance-methods – PM 2Ring Jul 19 '18 at 22:02
  • `Option('View goals', view)` ? – rafaelc Jul 19 '18 at 22:09
  • @PM2Ring yes, you're right. My terminology was wrong. – enumaris Jul 19 '18 at 22:10
  • Can you edit your code into a [mcve] that shows us how you want to use that class? Those methods are instance methods, so they ought to be called on an instance of the `Menu` class. – PM 2Ring Jul 19 '18 at 22:14

1 Answers1

0

Firstly, it seems like you want your methods to be 'staticmethods', since you're calling them directly through the class (and not an instance of the class.) It's also possible you want 'classmethods'. This answer will help you figure out which kind you want.

Secondly, you can't store unbound objects in this manner. See this answer.

Mudit Gupta
  • 66
  • 1
  • 2