{article Dive into Python}{title} {text} {/article}

Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:45:13) [MSC v.1600 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> class counter:
count = 0
def __init__(self):
self.__class__.count += 1


>>> counter
<class '__main__.counter'>
>>> counter.count
0
>>> c = counter()
>>> c.count
1
>>> counter.count
1
>>> d = counter()
>>> d.count
2
>>> c.count
2
>>> counter.count
2
>>>

count is a class attribute of the counter class.

__class__ is a built−in attribute of every class instance (of every class). It is a reference to the class that self is an instance of (in this case, the counter class).

Because count is a class attribute, it is available through direct reference to the class, before you have created any instances of the class.

Creating an instance of the class calls the __init__ method, which increments the class attribute count by 1. This affects the class itself, not just the newly created instance.

Creating a second instance will increment the class attribute count again. Notice how the class attribute is shared by the class and all instances of the class.

{source}
<!-- You can place html anywhere within the source tags -->
<link type="text/css" rel="Stylesheet" href="/styles/shThemeEmacs.css"/>
<pre class="brush:py;">

Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:45:13) [MSC v.1600 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> class counter:
        count = 0
        def __init__(self):
            self.__class__.count += 1


>>> counter
<class '__main__.counter'>
>>> counter.count
0
>>> c = counter()
>>> c.count
1
>>> counter.count
1
>>> d = counter()
>>> d.count
2
>>> c.count
2
>>> counter.count
2
>>>




</pre>

<script language="javascript" type="text/javascript">
    // You can place JavaScript like this

</script>
<?php
    // You can place PHP like this

?>
{/source}