![](/img/trans.png)
[英]Python allows for instances of the same class to have different sets of methods. Is it appropriate to have instances with different methods?
[英]Why is it sensible for two instances of the same class to have different attributes (Python)?
class Stock:
... def __init__(self, ticker, price):
... self.ticker = ticker
... self.price = price
...
>>> apple = Stock('APPL', 100)
>>> apple.ceo='tim cook'
>>> google = Stock('GOOG', 10)
現在,如果您比較dir(apple)
和dir(google)
, apple
實例將有一個額外的屬性ceo
。
但是, isinstance(apple,Stock)
和isinstance(google,Stock)
都是 True。
允許具有不同屬性的對象同時成為同一個 class 的實例背后的直覺是什么? 你什么時候用這個,實際上?
我會認為作為相同 class 實例的對象必須具有相同的屬性列表。
出於樣式原因,它通常沒有用,也不鼓勵使用,因為(在 CPython 中)它使每個實例使用更多的 memory(通過破壞密鑰共享字典)。
當它出現時,它通常用於緩存(計算一些可能並不總是使用的值很昂貴,但如果計算它以供重用,則應該存儲它),或者在 object 主要充當字符串鍵字典的情況下具有屬性訪問語義,類似於 JSON 對象( types.SimpleNamespace
服務於大多數此類情況)。
為了啟用這些(誠然不常見的)用例,大多數 Python 對象將它們的屬性存儲在引擎蓋下的dict
中,並且它們不會(太多)區分__init__
和其他時間的分配。
如果您不想要此功能,您可以通過在 class 上定義__slots__
來禁用任意屬性的創建,以明確描述合法屬性; 這將阻止創建任何其他屬性,並進一步減少每個實例 memory 對 class 的使用(甚至超過密鑰共享字典可以做的)。 在你的情況下,你會這樣做:
class Stock:
__slots__ = 'ticker', 'price'
def __init__(self, ticker, price):
self.ticker = ticker
self.price = price
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.