任何人都有实现要传递给函数的对象列表的好方法吗?所有对象都包含检查方法,但它们是不同类的对象。(对不起,我之前没有这么说)
这是 Python 的普通鸭子类型。
class Room:
def __init__(self, name):
self.name = name
def examine(self):
return "This %s looks clean!" % self.name
class Furniture:
def __init__(self, name):
self.name = name
def examine(self):
return "This %s looks comfortable..." % self.name
def examination(l):
for item in l:
print item.examine()
list_of_objects = [ Room("Living Room"), Furniture("Couch"),
Room("Restrooms"), Furniture("Bed") ]
examination(list_of_objects)
印刷:
This Living Room looks clean!
This Couch looks comfortable...
This Restrooms looks clean!
This Bed looks comfortable...
至于您的具体问题:可能您忘记从 ? 返回一个值examine()
?(请发布完整的错误消息(包括完整的回溯)。)
然后我有一个函数字典,我想将对象传递给函数。但是,我遇到了一些问题。例如,我有一个字典:
my_dict = {'look': CallLook(rooms[i])} # this is no dict of functions
dict
您创建的可能评估为{'look': None}
(假设您examine()
没有返回值。)这可以解释您观察到的错误。如果你想要一个函数的字典,你需要放入一个可调用的,而不是实际的函数调用,例如:
my_dict = {'look': CallLook} # this is a dict of functions
如果你想绑定'look'
到一个特定的room
你可以重新定义CallLook
:
def CallLook(current_room)
return current_room.examine # return the bound examine
my_dict = {'look': CallLook(room[i])} # this is also a dict of functions
dict()
您的代码的另一个问题是您通过命名本地字典来隐藏内置方法dict
。你不应该这样做。这会产生令人讨厌的错误。