在任何模块/对象上调用某个函数

2024-09-26 22:12:12 发布

您现在位置:Python中文网/ 问答频道 /正文

在JavaScript中,我有多个不同的模块(对象)和一个名为“one”的函数。你知道吗

test_module1 = { 
    one: function () {
       alert('fun mod1_one successful'); 
    },
    two: function () {
       alert('fun mod1_two successful'); 
    }
}
test_module2 = { 
    one: function () {
       alert('fun mod2_one successful'); 
    },
    two: function () {
       alert('fun mod2_two successful'); 
    }
}

workingObj = test_module1;
workingObj["one"]();

现在,如果变量“workingObj”中有一个模块/对象,我想调用 这个对象上的函数“one”,我称之为workingObj[“one”]();。你知道吗

现在我在学Python。这种语言有什么相似之处吗?你知道吗

我需要一个没有Python类/继承的解决方案。你知道吗

提前多谢

沃尔夫冈


Tags: 模块对象函数testfunctionalertjavascriptone
2条回答

当然!您所要做的就是利用“getattr”并执行以下操作

class MyObj(object):
    def func_name(self):
        print "IN FUNC!"

my_obj = MyObj()

# Notice the () invocation
getattr(my_obj, "func_name")() # prints "IN FUNC!"

你可以使用^{}

from operator import methodcaller
call_one = methodcaller("one")

现在可以使用get_one从任何对象获取one,并像这样调用它

call_one(obj)

优于getattr

除了它的可读性和习惯用法之外,您不必为每个对象调用methodcaller,不像getattr。创建一次,并使用它,只要你想与尽可能多的对象。你知道吗

例如

class MyClass1(object):  # Python 2.x new style class
    def one(self):
        print "Welcome"

class MyClass2(object):  # Python 2.x new style class
    def one(self):
        print "Don't come here"

from operator import methodcaller
call_one = methodcaller("one")

obj1, obj2 = MyClass1(), MyClass2()
call_one(obj1)    # Welcome
call_one(obj2)    # Don't come here

相关问题 更多 >

    热门问题