From: Costin GamenČ› on
Thank you all for your answers and your patience. As soon as I can,
I'll update my code and read up on the subject. If I still can't get
it working, I'll bother you again.
From: Mel on
Costin Gament wrote:

> So you're saying I should just use __init__? Will that get me out of
> my predicament?
> No, I don't quite understand the difference between my exemple and
> using __init__, but I will read the docs about it.

Here's the thing about class variables:

Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41)
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class AClass (object):
.... var = 5
....
>>> a = AClass()
>>> b = AClass()
>>> a.var, b.var
(5, 5)
>>> AClass.var = 7
>>> a.var, b.var
(7, 7)
>>> a.var = 9
>>> a.var, b.var
(9, 7)
>>> a.var is AClass.var
False
>>> b.var is AClass.var
True

When `var` is defined as a variable in AClass, it belongs to AClass. But
all the instances of AClass are allowed to access it as though it's their
own -- it's a sensible way for Python to manage attribute lookup.

Assigning to AClass.var changes the value as seen by all the instances.

Assigning to a.var creates a new variable in instance a's namespace, and
from then on that becomes the value that will be found by looking up a.var .
The `is` test shows that this is true.

Mel.


From: Steven D'Aprano on
On Sun, 08 Aug 2010 19:47:18 -0400, Mel wrote:

> Costin Gament wrote:
>
>> So you're saying I should just use __init__? Will that get me out of my
>> predicament?
>> No, I don't quite understand the difference between my exemple and
>> using __init__, but I will read the docs about it.
>
> Here's the thing about class variables:
[snip example]

No, that's actually the thing about class *attributes*. This is Python,
not Java or whatever language you're used to that uses such bizarrely
inconsistent terminology.

A variable holding an int is an int variable.

A variable holding a string is a string variable.

A variable holding a float is a float variable.

And a variable holding a class is a class variable.

Given a class:

class MyClass:
attribute = None

MyClass is a perfectly normal variable, like any other variable you
create in Python. You can reassign to it, you can pass it to functions,
it has an object bound to it. In other words, it's a class variable in
the same way that n = 2 creates an int variable.

(Although of course because Python has dynamic typing, n is only an int
until it gets rebound to something which isn't an int. Likewise MyClass
is only a class until it gets rebound to something else.)

That's why Python has builtin functions getattr, setattr and hasattr
rather than getvar, setvar and hasvar.


--
Steven
First  |  Prev  | 
Pages: 1 2 3 4
Prev: Renaming of files in OS directory
Next: DjangoCon 2010