Functions within classes in dictionary

Question

I am trying to place a function that was made in a class inside a dictionary but keep getting the error 'name 'eggs' is not defined. This is what i have tried so far,

class spam(object):
    def __init__(self,my_dict={'eggs',eggs}):
        self.my_dict=my_dict
    def eggs(self):
        print('eggs')

I have also tried using outside the class

class spam(object):
    def __init__(self,my_dict):
        self.my_dict=my_dict
    def eggs(self):
        print('eggs')

my_dict={'eggs':eggs}

I have also tried replacing that dictionary with:

{'eggs':eggs()}
{'eggs':spam.eggs}
{'eggs':spam.eggs()}

Can someone either tell me how to create this dictionary or another way to call this function based on a string input.


I am updating this to reply to all the answers offered so far, i have tried all of these and they all cause attribute errors; perhaps the issue is somewhere else in my code. The following is my actual code:

class archer(player):
def __init__(self,name,health=100,dammin=20,dammax=25,dodge=10,moves=['shot']):
    self.name=name
    self.health=health
    self.dammin=dammin
    self.dammax=dammax
    self.dodge=dodge
    self.moves=moves
    def shot(self):
        chance=random.randint(1,100)
        if chance >= 10:
            print('MISS')
            return False
        else:
            print('You fire your arrow')
            return True

all_moves={'shot':archer.shot}

Show source
| class   | python   | python-3.x   | dictionary   2017-01-07 21:01 3 Answers

Answers ( 3 )

  1. 2017-01-07 21:01

    You have to create an instance of the class to access that function. You can do this outside the class:

    {'eggs':spam().eggs}
    
  2. 2017-01-07 21:01

    Outside the class, eggs is a non-static class-method, so you can't access it without a class instance like

    {'eggs': spam().eggs}
    

    You may consider static-ing it, if you want to, using

    @staticmethod
    def eggs ():
        print('eggs')
    

    So stuff like {'eggs': spam.eggs} would work.

  3. 2017-01-07 21:01

    Create the dictionary inside __init__().

    class spam(object):
      def __init__(self, my_dict=None):
        if my_dict is None:
          my_dict = {'eggs': self.eggs}
        self.my_dict = my_dict
    

    If you want to store the original method and not the bound instance method, use spam.eggs or type(self).eggs (both having slightly different semantics).

◀ Go back