[Twisted-Python] Why classes in twisted.protocols.basic use "static member" to store states?

Phil Mayers p.mayers at imperial.ac.uk
Fri Mar 30 05:46:22 EDT 2007

甜瓜 wrote:
> No, I don't think so. ^_^ You can see it from the last lines in you
> recommend document:

No you can't, because you've misunderstood.

>>>> d.count
> 2
>>>> c.count
> 2
> Instance c & d indeed share the class attribute "count". You can try
> it more explicitly:
>>>> class A:
> ...     i = 0
> ...
>>>> p = A()
>>>> q = A()
>>>> A.i = 2
>>>> p.i
> 2
>>>> q.i
> 2
> Again, instance p & q share the class attribute "i".

They share it UNTIL IT IS MODIFIED. So, to continue the above example, 
the relevant bit would be:

 >>> p.i=3
 >>> p.i
 >>> q.i

Effectively, classes in python serve as templates to create instances. 
If you create two instances of a class and modify the class, then both 
are modified - however, if you then modify an instance, the class and 
other instances are not, and those modifications override any 
conflicting ones on the class.

Continuing the above example:

 >>> p.__dict__
{'i': 3}
 >>> q.__dict__

So, because we've modified "p", the attribute is set in the instance 
dict. q remains unmodified, and the getattr call will continue through 
to the class.

Doing this:

class AProtocol:

..is just a quick way to get INITIALSTATE set on every instance. The 
ONLY circumstance you need worry about these variables being shared is 
if you use a mutable variable and mutate it in place. For example:

 >>> class BProtocol:
...   SOMEDATA = {}
 >>> p = BProtocol()
 >>> q = BProtocol()
 >>> p.SOMEDATA['a'] = 1
{'a': 1}

If you don't want that to happen, don't do it. Twisted doesn't.

More information about the Twisted-Python mailing list