Python 物件導向 slots

2021-07-31 06:03:46 字數 610 閱讀 6119

預設情況下,python 用乙個字典來儲存乙個物件的例項屬性。這使得我們可以在執行的時候動態的給類的例項新增新的屬性:

test = test()

test.new_key = 'new_value'

然而這個字典浪費了多餘的空間 — 很多時候我們不會建立那麼多的屬性。因此通過slots可以告訴 python 不要使用字典而是固定集合來分配空間。

class

test

(object):

# 用列表羅列所有的屬性

__slots__ = ['name', 'value']

def__init__

(self, name='test', value='0'):

self.name = name

self.value = value

test = test()

# 此時再增加新的屬性則會報錯

test.new_key = 'new_value'

# attributeerror: 'test' object has no attribute 'new_key'

python 物件導向程式設計的 slots

同乙個類下,不同例項定義的屬性或者方法,其他例項如果沒有定義是不能使用的 定義乙個類 class student object pass 給類繫結乙個例項 s student 給例項繫結乙個屬性 s.name micheal s.name micheal s1 student s1.name 報錯a...

python物件導向程式設計高階篇 slots

python語言中我們可以隨時給例項增加新的屬性和方法 class student object pass s student s.name michael 動態給例項繫結乙個屬性 print s.name michael def set age self,age 定義乙個函式作為例項方法 self...

物件導向程式設計 使用 slots

學習廖雪峰老師的python教程中的使用 slots 的筆記 usr bin env python3 coding utf 8 class student object pass s student s.name michael 給例項繫結屬性 print s.name 給例項繫結方法 def se...