Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat in the world is the attribute "__class__" in python
    text
    copied!<p>I have a question about <code>__class__</code> in python.</p> <p>The documentation says that <code>__class__</code> is the class to which a class instance belongs. So I conducted a series of experiments:</p> <pre><code>class counter: count = 0 def __init__(self): self.__class__.count += 1 NewCounter1 = counter() print NewCounter1.count #The result is 1 NewCounter2 = counter() print NewCounter2.count #The result is 2 print NewCounter2.__class__.count is NewCounter2.count #result: True </code></pre> <p>Everything goes well.</p> <p>Then I enter code as follows:</p> <pre><code>NewCounter2.__class__.count = 3 print NewCounter1.count #result:3 print NewCounter1.__class__.count #result:3 print NewCounter2.count #result:3 print NewCounter2.__class__.count #result:3 print NewCounter2.__class__.count is NewCounter2.count #result: True </code></pre> <p>From the code above, I thought that maybe <code>NewCounter1.count</code> equals <code>NewCounter1</code>, or <code>__class__.count</code>, but the following code surprised me:</p> <pre><code>NewCounter2.count = 5 print NewCounter1.count #result:3 print NewCounter1.__class__.count #result:3 print NewCounter2.count #result:5 print NewCounter2.__class__.count #result:3 print NewCounter2.__class__.count is NewCounter2.count #result: False </code></pre> <p>Why has <code>NewCounter2.count</code> changed but <code>NewCounter2.__class__.count</code> remained at 3? What's more, when I changed <code>NewCounter2.count</code>, <code>NewCounter2.__class__.count is NewCounter2.count</code> became <code>False</code>. What in the world is the attribute <code>__class__</code> ?</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