Cailean Allway
Cailean Allway

Reputation: 11

Functions within classes in dictionary

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.

Upvotes: 1

Views: 1382

Answers (3)

Uriel
Uriel

Reputation: 16184

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.

Upvotes: 1

Niklas R
Niklas R

Reputation: 16870

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

Upvotes: 1

ForceBru
ForceBru

Reputation: 44838

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

{'eggs':spam().eggs}

Upvotes: 1

Related Questions