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) 也可以存取類別屬性,如下例
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.")
# 《程式語言教學誌》的範例程式
# http://pydoing.blogspot.com/
# 檔名:cla11.py
# 功能:示範 Python 程式
# 作者:張凱慶
# 時間:西元 2010 年 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)
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.")
# 《程式語言教學誌》的範例程式
# http://pydoing.blogspot.com/
# 檔名:cla12.py
# 功能:示範 Python 程式
# 作者:張凱慶
# 時間:西元 2010 年 12 月 執行結果如下

| 中英文術語對照 | |
|---|---|
| 類別 | class |
| 屬性 | attribute |
| 類別屬性 | class attribute |
| 實體屬性 | instance attribute |
| 識別字 | identifier |
| 物件 | object |
參考資料
http://docs.python.org/py3k/tutorial/classes.html
http://docs.python.org/py3k/reference/compound_stmts.html
http://docs.python.org/py3k/tutorial/classes.html
http://docs.python.org/py3k/reference/compound_stmts.html
沒有留言:
張貼留言