简体   繁体   中英

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 .

however, isinstance(apple,Stock) and isinstance(google,Stock) are both True.

What is the intuition behind allowing objects with different attributes to both be instances of the same 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.

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 ).

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 ).

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.

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; 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). In your case, you'd do this with:

class Stock:
    __slots__ = 'ticker', 'price'
    def __init__(self, ticker, price):
        self.ticker = ticker
        self.price = price

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM