[Tutor] How to set variables inside a class()

Dominik George nik at naturalnet.de
Tue Nov 26 12:13:52 CET 2013


Hi,

> By setting test.flag you are creating a new instance level attribute
> that exists only within the test instance. That's legal Python
> but usually its not a good idea to have different instances of
> the same class having different attributes.

maybe this becomes clearer by breaking down the whole thing to something
more basic: dictionaries.

As I mentioned before, classes and their instances are more or less
dictionaries containing their attributes.

When you set a variable at class scope (like your flag in the class
definition), then this is added to the dictionary of the class.

Now when zou instantiate the class, then the dictionary is copied to the
instance (carying references to the same data inside it, mind you!), so
the instance has an attribute called flag available, pointing to the
same data as the flag in the class.

You can do things such as:

   my_instance.f = False

or

   self.f = False

This will then assign the *new* data to the named attribute in the
instance, thus releasing that reference to the class' attribute data.

And that's all of the magic - shallow copies of a dictionary that you
sometimes overwrite. There's not much more to static attributes in
Python.

You can prove this by manipulating the copy of a class attribute in an
isntance without replacing it, like so:

   class C():
       entries = []

   c = C()
   c.entries.append('foo')

   c.entries
   C.entries

You will find that both the last lines return the same thing - the list
with 'foo' appended, because you just manipulated the same list object
in place.

One last thing, when you create an instance-level attribute, you do that
inside a method by adding it to the self reference. This only adds it to
the dictionary of that instance - normally, you setup all attributes in
the constructor because that guarantees that they are set for all new
instances.

You could as well use class-level attributes to initialize attributes
for all instances, but as noted above, you must pay very close attention
then because if you happen to manipulate such an attribute in place in
one class before replacing it, you manipulate it for all other
isntances, too.

-nik

-- 
Wer den Grünkohl nicht ehrt, ist der Mettwurst nicht wert!

PGP-Fingerprint: 3C9D 54A4 7575 C026 FB17  FD26 B79A 3C16 A0C4 F296
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 905 bytes
Desc: Digital signature
URL: <http://mail.python.org/pipermail/tutor/attachments/20131126/1e8dfa0f/attachment.sig>


More information about the Tutor mailing list