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

內建函數 (function) hasattr() ,判斷參數 (parameter) name 是否為 object 的屬性名稱

函數描述
hasattr(object, name)判斷 name 是否為 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(hasattr(d, "t"))
print(hasattr(d, "u"))
print(hasattr(d, "v"))
print(hasattr(d, "w"))
print(hasattr(d, "x"))
print(hasattr(d, "y"))
print(hasattr(d, "z"))
 
# 《程式語言教學誌》的範例程式
# 檔名:hasattr.py
# 功能:示範 Python 程式
# 作者:張凱慶
# 時間:西元 2010 年 12 月


執行結果如下



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


內建函數




沒有留言: