简体   繁体   English

为什么相同 class 的两个实例具有不同的属性(Python)是明智的?

[英]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.

相关问题 Python允许同一类的实例具有不同的方法集。 使用不同方法的实例是否合适? - Python allows for instances of the same class to have different sets of methods. Is it appropriate to have instances with different methods? 为什么具有相同`id`的两个函数具有不同的属性? - Why can two functions with the same `id` have different attributes? 如何在REPL中测试同一类的两个实例是否具有相同的属性? - How can I test in REPL whether two instances of the same class have the same attributes? 为什么python允许为同一个类创建不同的属性集? - Why does python allow to make different set of attributes for same class? 在 python 中,相同 class 的两个不同对象可以有不同的变量数 - In python can two different objects of same class have different no of variables 为什么这个类变量在不同的实例中是相同的? - Why is this class variable the same across different instances? 如何检查两个实例是否属于同一类Python - How to check if two instances are of the same class Python 为什么这两个几乎相同的代码具有不同的效率(Python)? - Why these two almost same codes have different efficient (Python)? 类 A 的实例作为 Python 中 A 的类属性? - Instances of class A as class attributes of A in Python? 为什么属性必须是Python中的类属性? - Why do properties have to be class attributes in Python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM