class class_name:
def foo1(self):
print "foo1"
def foo2(self):
print "foo2"
def foo(self, key):
self.dictionary[key]()
dictionary = {
'key1' : class_name.foo1,
'key2' : class_name.foo2
}
>>>class_name().foo('key1')
Error: AttributeError: class_name instance has no attribute 'dictionary'
Although I understand the error, I do not know how to rectify it.
Even if I define the dictionary inside the class "by indenting it to be inside the class definition, it then generates the error that NameError: name 'class_name' is not defined"*
Any advice on how to fix this is appreciated.
EDIT: I need a single dictionary for the class, not one dictionary per object instance
A little insight into the real problem: I am making a chess game. So while defining the game logic, each piece has its own style of moving. I wished to call a single function to give me the legal moves as per the current state of the chess board. This single function (in the example foo()) has to call other functions based on the type of the piece and also provide those functions with the object instance (and other parameters), so that they can compute the moves. The problem I face is to pass the object instance to the piece specific functions (foo1() and foo2()).
Maybe this will help. This is what I want to achieve in the function foo()
:
switch(key){
case 'key1':
self.foo1();
break;
case 'key2':
self.foo2();
break;
}
* added from comment