Python函数指针在同一个Class内 [英] Python function pointers within the same Class

查看:159
本文介绍了Python函数指针在同一个Class内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Python中有以下类,我试图通过一个带有可用函数指针的字典调用一组自己的方法:

I have the following class in Python that I am trying to use for calling a set of its own methods through a dictionary that has the pointers of the available functions:

class Test():

    functions = {
        'operation_a' : Test.function_a;
        'operation_b' : Test.function_b;
    }

    def run_operations(operation, *args, **kwargs):

        try:
            functions[str(operation)](self, args, kwargs)
        except KeyError:
            // some log ...

    def function_a(self, *args, **kwargs):
        print A

    def function_b(self, *args, **kwargs):
        print B

由于Python解释器找不到类'Test'(NameError:'Test'未定义),所以第一种方法似乎不正确。我无法找到一种方法(从package.module import * ...等)导入包,包和模块,)。因此,我有3种解决方案这个问题已经为我工作:
$ b

This first approach seems to be incorrect since the Python interpreter cannot find class 'Test' (NameError: 'Test' is not defined). I could not find a way (either importing the package, the package and the module, from package.module import *... etc.) Therefore, I have 3 solutions for this issue that already worked for me:


  1. 定义类构造函数中的操作字典( __ init __() code>),
  2. 将可调用的函数移动到不同的类中(在我的例子中,该类位于不同的模块中,我没有尝试使用同一个模块中的类),
  3. 在同一个类中定义了@staticmethod函数

然而,我仍然不知道为什么最初的方法似乎不正确。因此,如何在实例化之前引用同一类中的函数?

However, I still do not know why the initial approach does not seem to be correct. Therefore, how can I reference to a function within the same class before instantiation?

推荐答案

类对象在类声明的正文结束之前不存在。但是这些函数在def语句正文后面的命名空间中可用。所以你想要的是:

The class object doesn't exist before the end of the class statement's body. But the functions are available in the namespace after the def statement's body. So what you want is:

class Test(object):

    def run_operations(self, operation, *args, **kwargs):
        try:
            function = self.functions[operation]
        except KeyError:
            # some log ...
        else:
            function(self, args, kwargs)

    def function_a(self, *args, **kwargs):
        print "A"

    def function_b(self, *args, **kwargs):
        print "B"

    functions = {
        'operation_a' : function_a,
        'operation_b' : function_b,
        }

编辑:也可以使用 getattr 和当前实例和方法名称来获取方法,但这意味着所有方法都成为潜在的'操作',这既不明显,也存在潜在的安全问题。通过明确地选择合法操作来继续使用getattr的一种方法是仅向相关函数添加标记,即:

edit: As alko mentionned, you could also use getattr with the current instance and method name to get the method, but it means all methods become potential 'operations', which is both unexplicit and a potential security issue. One way to still use getattr with explicit "selection" of the legit operations is to just add a marker to the relevant functions, ie:

def operation(func):
    func.is_operation = True
    return func

class Test(object):
    def run_operations(self, operation, *args, **kwargs):
        method = getattr(self, operation, None)
        if method is None:
            # raise or log or whatever
        elif not method.is_operation:
            # raise or log or whatever
        else:
            method(*args, **kwargs)

    @operation
    def operation_a(self, *args, **kwargs):
        print "A"

    @operation
    def operation_b(self, *args, **kwargs):
        print "B"

    def not_an_operation(self):
        print "not me"

另一种解决方案是使用内部类作为命名空间来执行操作,即:

Yet another solution is to use an inner class as namespace for the operations, ie:

class Test(object):

    def run_operations(self, operation, *args, **kwargs):
        method = getattr(self.operations, operation, None)
        if method is None: 
            # raise or log or whatever
        else:
            method(self, *args, **kwargs)

    class operations(object):
        @classmethod
        def operation_a(cls, instance, *args, **kwargs):
            print "A"

        @classmethod
        def operation_b(cls, instance, *args, **kwargs):
            print "B"

还有其他可能的解决方案。哪一个最好取决于您的需求,但除非您构建框架,否则基于字典的框架尽可能简单,易读和高效。

There are still other possible solutions. Which one is "best" depends on your needs, but unless you're building a framework the dict-based one is as simple, readable and effective as possible.

这篇关于Python函数指针在同一个Class内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆