简体   繁体   English

如何使用类中的函数创建字典?

[英]How to create a dict with functions from a class?

I have a class like this:我有这样的课程:

class example:
    def func1:
        print('bla bla')

    def func2:
        print('bla bla 2')

Now I want a dict with all the functions in the class like so:现在我想要一个包含类中所有函数的字典,如下所示:

{'func1': <function example.func1 at 0xBLABLA>,
'func2': <function example.func2 at 0xBLABLA2>}

I think that are pointers but I don't know.我认为那是指针,但我不知道。

And I don't want to create the dict manually.而且我不想手动创建字典。 It should be created automatically.它应该自动创建。

So how can I do this?那我该怎么做呢?

This will do, filtering only callables form the class __dict__ :这样做,只过滤来自类__dict__的可调用对象:

>>> {k:v for k,v in Example.__dict__.items() if callable(v)}
{'foo1': <function Example.foo1 at 0x7fe2ce405840>, 'foo2': <function Example.foo2 at 0x7fe2cb304ea0>}

Firstly, class names start with a uppercase;首先,类名以大写字母开头; whilst the functions need to have the self argument or mark them as static which would still require you to add parenthesis as shown below.虽然函数需要有self参数或将它们标记为static ,但仍需要您添加括号,如下所示。

class Example:
    def func1(self):
        print('bla bla')

    def func2(self):
        print('bla bla 2')

Manual - Addition to achieve what you want:手动 - 添加以实现您想要的:

my_functions = {
    Example.func1,
    Example.func2
}

print(my_functions)

Output:输出:

{<function example.func2 at 0x7fc5f160e620>, <function example.func1 at 0x7fc5f160e6a8>}

Automatic - Addition to achieve what you want:自动 - 添加以实现您想要的:

functions = {}
for name, value in Example.__dict__.items():
    if callable(value):
        functions[name] = value

print(functions)

Output:输出:

{'func1': <function Example.func1 at 0x7f58c24c26a8>, 'func2': <function Example.func2 at 0x7f58c24c2620>}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM