- 回傳物件裡的屬性
- Python的內建函數
- Example1
class Demo:
def __init__(self):
self.x = "demo_x"
self.y = "demo_y"
def test(self):
print "demo_test"
demo = Demo()
print getattr(demo, "__init__")
print getattr(demo, "x")
print getattr(demo, "y")
def __init__(self):
self.x = "demo_x"
self.y = "demo_y"
def test(self):
print "demo_test"
demo = Demo()
print getattr(demo, "__init__")
print getattr(demo, "x")
print getattr(demo, "y")
執行結果
- Example2
class WebService:
def __init__(self):
self.demos = []
def register(self, demo)
self.demos.append(demo)
def exe(self, func):
for demo in demos.values():
function = getattr(demo, func)
return function(parms)
class Demo():
def _exe1(self, parms):
print "_exe1: %s " % parms
def _exe2(self, parms):
print "_exe2: %s" % parms
ws = WebService()
ws.register(Demo())
ws.exe('_exe1')
Reference:
[1] Python 3.1 快速導覽 - 內建函數 getattr()
沒有留言:
張貼留言