2017-05-11 48 views
1

我有一個定義了下列字符串,它們指定了一個python模塊名稱,一個python類名稱和一個靜態方法名稱。如何在類內通過字符串方法名稱調用python靜態方法

module_name = "com.processors" 
class_name = "FileProcessor" 
method_name = "process" 

我想調用由METHOD_NAME變量指定的靜態方法。

我如何在Python實現這一2.7+

+0

[這](http://stackoverflow.com/questions/3849576/how -to-call-a-static-method-a-class-using-method-name-and-class-name)可能會有一些幫助! – Iggydv

回答

3

使用__import__功能通過給導入模塊模塊名稱作爲字符串。

使用getattr(object, name)從對象(模塊/類或anything

這裏訪問名稱u能做到

module = __import__(module_name) 
cls = getattr(module, claas_name) 
method = getattr(cls, method_name) 
output = method() 
1

您可以使用導入庫這一點。 嘗試importlib.import(module +"." + class +"."+ method)

請注意,此連接字符串應該完全一樣,如果你將通過進口module.class.method

1

導入試試這個:

# you get the module and you import 
module = __import__(module_name) 

# you get the class and you can use it to call methods you know for sure 
# example class_obj.get_something() 
class_obj = getattr(module, class_name) 

# you get the method/filed of the class 
# and you can invoke it with method() 
method = getattr(class_obj, method_name) 
相關問題