Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Impossible.</p> <pre><code>id(c1) == id(c2) </code></pre> <p>says that <code>c1</code> and <code>c2</code> are references to the exact same object. So </p> <p><code>c2.suit = 's'</code> is exactly the same as saying <code>c1.suit = 's'</code>.</p> <p>Python has no way of distinguishing the two (unless you allow introspection of prior call frames, which leads to a dirty hack.)</p> <p>Since the two assignments are identical, there is no way for Python to know that <code>c2.suit = 's'</code> should cause the <strong>name</strong> <code>c2</code> to reference a different object.</p> <hr> <p>To give you an idea of what the dirty hack would look like,</p> <pre><code>import traceback import re import sys import weakref class Card(object): _CardPool = weakref.WeakValueDictionary() def __new__(cls, value, suit): obj = Card._CardPool.get(value + suit, None) if not obj: obj = object.__new__(cls) Card._CardPool[value + suit] = obj obj._value, obj._suit = value, suit return obj @property def suit(self): return self._suit @suit.setter def suit(self, suit): filename,line_number,function_name,text=traceback.extract_stack()[-2] name = text[:text.find('.suit')] setattr(sys.modules['__main__'], name, Card(self._value, suit)) c1 = Card('10', 'd') c2 = Card('10', 'd') assert id(c1) == id(c2) c2.suit = 's' print(c1.suit) # 'd' assert id(c1) != id(c2) </code></pre> <p>This use of traceback only works with those implementations of Python that uses frames, such as CPython, but not Jython or IronPython.</p> <p>Another problem is that </p> <pre><code>name = text[:text.find('.suit')] </code></pre> <p>is extremely fragile, and would screw up, for example, if the assignment were to look like</p> <pre><code>if True: c2.suit = 's' </code></pre> <p>or </p> <pre><code>c2.suit = ( 's') </code></pre> <p>or</p> <pre><code>setattr(c2, 'suit', 's') </code></pre> <p>Yet another problem is that it assumes the name <code>c2</code> is global. It could just as easily be a local variable (say, inside a function), or an attribute (<code>obj.c2.suit = 's'</code>). </p> <p>I do not know a way to address all the ways the assignment could be made.</p> <p>In any of these cases, the dirty hack would fail.</p> <p>Conclusion: Don't use it. :)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload