2011-04-05 60 views
1

我想出了這個解決方案。但是這看起來太複雜了。必須有更好更簡單的方法。第二:有沒有辦法動態地導入類?調用一個類的方法,類名是一個變量

class_name = "my_class_name"    # located in the module : my_class_name.py 
import my_class_name from my_class_name   

my_class = globals()[class_name] 
object = my_class() 
func = getattr(my_class,"my_method") 
func(object, parms)       # and finally calling the method with some parms 

回答

1

看看內置函數__import__。它確實如你所期望的那樣。

編輯:如承諾,這裏是一個例子。不是很好,我只是有壞消息,我的頭在別處,所以你可能會寫一個更實用的更適合你的上下文的更聰明的應用程序。至少,它說明了這一點。

>>> def getMethod(module, cls, method): 
...  return getattr(getattr(__import__(module), cls), method) 
... 
>>> getMethod('sys', 'stdin', 'write') 
<built-in method write of file object at 0x7fcd518fa0c0> 

編輯2:這是一個更聰明的。

>>> def getMethod(path): 
...  names = path.split('.') 
...  return reduce(getattr, names[1:], __import__(names[0])) 
... 
>>> getMethod('sys.stdin.write') 
<built-in method write of file object at 0x7fdc7e0ca0c0> 

你還在嗎?

+0

我試過了,但我想不出來 – voscausa 2011-04-06 00:03:16

+0

給我一會兒,我會寫一個例子併發布它 – slezica 2011-04-06 00:35:52

+0

你走了。希望能幫助到你。 – slezica 2011-04-06 00:39:35