如果我没听错,您可以简单地使用内置函数dir()。示例:
>>> class Foo(object):
... def m1(self):
... pass
... def m2(self):
... pass
...
>>> dir(Foo)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'm1', 'm2']
>>> [m for m in dir(Foo) if '__' not in m]
['m1', 'm2']
编辑:您的问题和您的 cmets 并不是很清楚。如果您可以编辑提及预期结果的问题,这将有所帮助。我最好的猜测是,在下面阅读您的评论(“我需要这本字典 {int type: method type}”)可能是您想要的:
>>> dict(enumerate([getattr(Foo, m) for m in dir(Foo) if '__' not in m]))
{0: <unbound method Foo.m1>, 1: <unbound method Foo.m2>}
EDIT2:查看您最新的 pastebin,当您编写时:
packet_ids_to_check_up = (0x0404, 0x0405, 0x0404, 0x0505, 0x0506)
for packet_id in packet_ids_to_check_up:
if packet_id in some_class_obj:
some_class_obj[packet_id]('Hello world')
您似乎希望您的班级充当字典。如果是这种情况,您可能应该查看collections.abc 模块,尤其是MutableMapping 类。来自python glossary:
mapping - 支持任意键查找并实现 Mapping 或 MutableMapping 抽象基类中指定的方法的容器对象。示例包括 dict、collections.defaultdict、collections.OrderedDict 和 collections.Counter。
这意味着实现以下方法:
__contains__
keys
items
values
get
__eq__
__ne__
pop
popitem
clear
update
setdefault
但是,从您的代码来看,为什么您不能只使用简单的字典(或最终直接继承 dict...),这并不是不言而喻的。
这有帮助吗?