類別定義
class 類別名:
例如:
>>> class Point:
... x = 0.0
... y = 0.0
1. 宣告
>>> p1 = Point()
>>> p1.x, p1.y
(0.0, 0.0)
2. 賦値
>>> p1.x = 5.0
>>> p1.y = 6.0
>>> p1.x, p1.y
(5.0, 6.0)
3. 位址指向
>>> p1
<__main__.Point object at 0x00000000021B22E8>
>>> id(p1.x)
30060832
>>> id(p1.y)
30060808
4. 別名 Alias
>>> p2 = p1
>>> id(p1)
35332840
>>> id(p2)
35332840
>>> p1 == p2
True
5. 複製 Copy
>>> id(p1)
35332840
>>> import copy
>>> p3 = copy.copy(p1)
>>> id (p3)
35332952
>>> p1 == p3
False
6. 物件嵌入物件
>>> class Phone:
... area_code = 0
... number = 0
...
>>> class Person:
... name = ''
... age = 0
... phone = Phone()
...
>>> p1 = Person()
>>> p1.name = 'John'
>>> p1.age = 20
>>> p1.phone.code = 2
>>> p1.phone.number = 995576
>>> id(p1)
31859152
>>> p2 = Person()
>>> p2.name = 'Mary'
>>> p2.age = 38
>>> p2.phone.code = 3
>>> p2.phone.number = 773322
>>> id(p2)
31859264
>>> import copy
>>> print(p1.name,p1.age,p1.phone.code,p1.phone.number)
John 20 3 773322
>>> print(p2.name,p2.age,p2.phone.code,p2.phone.number)
Mary 38 3 773322
>>>
注意到沒? 雖然 p1 與 p2 是不同的物件,但卻共享相同的物件 Phone,所以 p2.Phone 更新時, p1.Phone 也同樣更新,p1.Phone 與 p2.Phone 共享一個位址。
事實上 p1 與 p2 的 Phone 並沒有在 RAM 中被分配 Allocate 空間存儲,所以才有這現象。我們必須以 p1.Phone() 與 p2.Phone() 各自分配存儲空間,例如:
>>> p1.phone = Phone()
>>> p1.phone.code = 2
>>> p1.phone.number = 995576
>>> print(p1.name,p1.age,p1.phone.code,p1.phone.number)
John 20 2 995576
>>> p2.phone = Phone()
>>> p2.phone.code = 3
>>> p2.phone.number = 773322
>>> print(p2.name,p2.age,p2.phone.code,p2.phone.number)
Mary 38 3 773322
>>>
7. 物件複製 Copy
>>> import copy
>>> p2 = copy.copy(p1)
>>> print(p1.name,p1.age,p1.phone.code,p1.phone.number)
John 20 2 995576
>>> print(p2.name,p2.age,p2.phone.code,p2.phone.number)
John 20 2 995576
>>> id(p1)
31859152
>>> id(p2)
31859656
>>> p1 == p2
False
/end