Python 3.1 快速導覽 - 類別屬性與實體屬性

Python 類別 (class) 的屬性 (attribute) 有兩種,一種是類別屬性 (class attribute) ,另一種是實體屬性 (instance attribute) ,如下的 Demo 類別的定義

1
2
3
4
5
6
7
8
9
10
11
12
class Demo:
    i = 0
     
    def __init__(self, i):
        self.i = i
        Demo.i += 1
     
    def __str__(self):
        return str(self.i)
          
    def hello(self):
        print("hello", self.i)


i 為類別屬性, self.i 則為實體屬性。


兩者有何差別呢?通常類別屬性需要用類別名稱來存取,但若兩者的識別字 (identifier) 不同,實體物件 (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
29
30
31
32
33
34
35
36
37
class Demo:
    x = 0
     
    def __init__(self, i):
        self.i = i
        Demo.x += 1
     
    def __str__(self):
        return str(self.i)
          
    def hello(self):
        print("hello", self.i)
 
print("There are", Demo.x, "instances.")
a = Demo(1122)
a.hello()
print("a.x =", a.x)
b = Demo(3344)
b.hello()
print("b.x =", b.x)
c = Demo(5566)
c.hello()
print("c.x =", c.x)
d = Demo(7788)
d.hello()
print("d.x =", d.x)
e = Demo(9900)
e.hello()
print("e.x =", e.x)
print("After all, there are", Demo.x, "instances.")
 
# 《程式語言教學誌》的範例程式
# 檔名:cla11.py
# 功能:示範 Python 程式
# 作者:張凱慶
# 時間:西元 2010 年 12 月


執行結果如下



若是類別屬性與實體屬性的識別字相同,實體物件只能存取實體屬性,如下例
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
29
30
31
32
33
34
35
36
37
class Demo:
    i = 0
     
    def __init__(self, i):
        self.i = i
        Demo.i += 1
     
    def __str__(self):
        return str(self.i)
          
    def hello(self):
        print("hello", self.i)
 
print("There are", Demo.i, "instances.")
a = Demo(1122)
a.hello()
print("a.i =", a.i)
b = Demo(3344)
b.hello()
print("b.i =", b.i)
c = Demo(5566)
c.hello()
print("c.i =", c.i)
d = Demo(7788)
d.hello()
print("d.i =", d.i)
e = Demo(9900)
e.hello()
print("e.i =", e.i)
print("After all, there are", Demo.i, "instances.")
 
# 《程式語言教學誌》的範例程式
# 檔名:cla12.py
# 功能:示範 Python 程式
# 作者:張凱慶
# 時間:西元 2010 年 12 月


執行結果如下



中英文術語對照
類別class
屬性attribute
類別屬性class attribute
實體屬性instance attribute
識別字identifier
物件object






沒有留言: