1. 程式人生 > 實用技巧 >python通過例項方法名字的字串呼叫方法

python通過例項方法名字的字串呼叫方法

目錄

方式1 - 反射

hasattr 方法

判斷當前例項中是否有著字串能對映到的屬性或者方法, 一般會在 getattr 之前作為判斷防止報錯

getattr 方法

獲取到當前例項中傳入字串對映到的屬性或者方法

示例

class A(object):
    def run(self):
        return "run"
​
​
a = A()
​
print hasattr(a, "run")         # True
print getattr(a, "run")         # <bound method A.run of <__main__.A object at 0x0000000002A57160>>
print getattr(a, "run")() # run

方式2 - operator 模組

methodcaller 方法

引數

傳入兩個引數, 分別為字串表示對映的方法, 另一個引數為此方法的執行引數,

返回值

返回一個 字串對映到的方法例項

示例

import operator
​
​
class A(object):
    def run(self):
        return "run"def eat(self, s):
        return s + ": eat"
​
​
a = A()
​
print operator.methodcaller("
run") # <operator.methodcaller object at 0x0000000002ADAC08> print operator.methodcaller("run")(a) # run print operator.methodcaller("eat", "yangtuo")(a) # yangtuo: eat

方式3 - eval 模組

eval雖然方便,但是要注意安全性,可以將字串轉成表示式並執行,就可以利用執行系統命令,刪除檔案等操作。
假設使用者惡意輸入。比如:

eval("__import__('os').system('ls /Users/chunming.liu/Downloads/')
")

那麼eval()之後,你會發現,當前資料夾檔案都會展如今使用者前面。這句其實相當於執行了

os.system('ls /Users/chunming.liu/Downloads/')

不建議使用,因此此處不做示例