Python 3.1 快速導覽 - 內建函數 getattr()

內建函數 (function) getattr() ,取得參數 (parameter) object 的屬性值, name 為屬性名稱,必須為字串

函數描述
getattr(object, name[, default])取得 object 的屬性值


舉例示範如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Demo:
    def __init__(self, i):
        self.i = i
        self.x = "xxx"
        self.y = "yyy"
        self.z = "zzz"
     
    def __str__(self):
        return str(self.i)
          
    def hello(self):
        print("hello " + self.__str__())
 
d = Demo(22)
print(getattr(d, "__init__"))
print(getattr(d, "i"))
print(getattr(d, "x"))
print(getattr(d, "y"))
print(getattr(d, "z"))
print(getattr(d, "__str__"))
print(getattr(d, "hello"))
 
# 《程式語言教學誌》的範例程式
# 檔名:getattr.py
# 功能:示範 Python 程式
# 作者:張凱慶
# 時間:西元 2010 年 12 月


執行結果如下



中英文術語對照
函數function
參數parameter


內建函數




沒有留言: