[Tutor] Shared Class Attribute

Eric Brunson brunson at brunson.com
Wed Aug 29 00:18:15 CEST 2007


Ricardo Aráoz wrote:
> Hi,
>   

Hi Ricardo,

In the future, please start a new thread with a new email and not a 
reply to an existing thread.  Compliant mail clients thread based on 
headers you may or may not see in your client, and this email is part of 
the thread you replied to called "[Tutor] PyCon 2008 - Call for Tutorial 
Ideas".  In addition, you send a copy of your message to 
pycon-tutorials at python.org and many who reply using a "Reply All" 
function in their mailer will spam that list, too.

> if I have this class :
>
> class myClass :
>     ClassCount = 0
>     def __init__(self) :
>         (here I want to increment ClassCount for the whole class)
> 	self.InstanceAttr = 1
>   

You always reference a class variable by the class name:

 >>> class myclass:
...     count = 0
...     def __init__( self ):
...         myclass.count += 1
...
 >>> c = myclass()
 >>> print c.count
1
 >>> d = myclass()
 >>> print d.count
2
 >>> print c.count
2
 >>> e = myclass()
 >>> print e.count, myclass.count
3 3

Hope that helps.

Sincerely,
e.

> How would I increment the shared class attribute (ClassCount) from
> INSIDE the class?
> I can do it from the outside by stating myClass.ClassCount = 22 and it
> will change for all instances. But haven't found a way to do it from inside.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   



More information about the Tutor mailing list