如果假設我有一個類名作爲字符串,我如何使用反射來調用它之前已知的靜態成員?一些這樣的:Python:使用反射來從類名稱中調用類成員
someInspectionMechanism("FooClass").staticMethod()
如果假設我有一個類名作爲字符串,我如何使用反射來調用它之前已知的靜態成員?一些這樣的:Python:使用反射來從類名稱中調用類成員
someInspectionMechanism("FooClass").staticMethod()
使用locals()
或globals()
獲得命名空間的字典,尋找你想要的名稱的類。您使用靜態方法的事實不相關。
例子:
class Test:
@staticmethod
def method():
return 'called static method'
assert locals()['Test'].method() == 'called static method'
事實上,這是一個靜態方法_is_相關,因爲他否則需要實例化對象。 – 2012-02-26 15:41:04
是的,但它與獲得課程無關。 – 2012-02-26 15:50:30
沒有爲類沒有全局命名空間(這是一件好事),所以你最好知道它的位置。 – delnan 2012-02-26 15:33:38
你的意思是這樣的:http://stackoverflow.com/questions/4030982/initialise-class-object-by-name – Nobody 2012-02-26 15:34:41