[英]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)
now if you compare dir(apple)
and dir(google)
the apple
instance will have an extra attribute ceo
.现在,如果您比较
dir(apple)
和dir(google)
, apple
实例将有一个额外的属性ceo
。
however, isinstance(apple,Stock)
and isinstance(google,Stock)
are both True.但是,
isinstance(apple,Stock)
和isinstance(google,Stock)
都是 True。
What is the intuition behind allowing objects with different attributes to both be instances of the same class?允许具有不同属性的对象同时成为同一个 class 的实例背后的直觉是什么? When do you use this, practically?
你什么时候用这个,实际上?
I would have thought that objects that are instances of the same class must have the same list of attributes.我会认为作为相同 class 实例的对象必须具有相同的属性列表。
It's generally not useful, and discouraged, both for style reasons, and because (in CPython) it makes each instance use more memory (by breaking key-sharing dictionaries ).出于样式原因,它通常没有用,也不鼓励使用,因为(在 CPython 中)它使每个实例使用更多的 memory(通过破坏密钥共享字典)。
When it comes up, it's usually either for caches (some expensive to compute value that might not always be used, but should be stored if it is computed for reuse), or in cases where the object is mostly acting as a string-keyed dictionary with attribute access semantics, similar to JSON objects ( types.SimpleNamespace
serves for most such cases ).当它出现时,它通常用于缓存(计算一些可能并不总是使用的值很昂贵,但如果计算它以供重用,则应该存储它),或者在 object 主要充当字符串键字典的情况下具有属性访问语义,类似于 JSON 对象(
types.SimpleNamespace
服务于大多数此类情况)。
To enable these (admittedly uncommon) use cases, most Python objects store their attributes in a dict
under the hood, and they don't distinguish (much) between assignments in __init__
and at other times.为了启用这些(诚然不常见的)用例,大多数 Python 对象将它们的属性存储在引擎盖下的
dict
中,并且它们不会(太多)区分__init__
和其他时间的分配。
If you don't want this feature, you can disable creation of arbitrary attributes by defining __slots__
on your class to explicitly describe the legal attributes;如果您不想要此功能,您可以通过在 class 上定义
__slots__
来禁用任意属性的创建,以明确描述合法属性; this will prevent creation of any other attributes, and further reduce the per-instance memory usage of your class (even more than key-sharing dictionaries can do).这将阻止创建任何其他属性,并进一步减少每个实例 memory 对 class 的使用(甚至超过密钥共享字典可以做的)。 In your case, you'd do this with:
在你的情况下,你会这样做:
class Stock:
__slots__ = 'ticker', 'price'
def __init__(self, ticker, price):
self.ticker = ticker
self.price = price
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.