idiom for initialising variables
Erik Max Francis
max at alcyone.com
Wed Nov 6 14:11:15 EST 2002
Rob Hall wrote:
> I'm just wondering on the correct python idiom for initialising
> variables.
> I see some code like this:
>
> class myClass:
> self.a = 1
> def __init__(self):
> ...more stuff here
This is illegal. You probably meant:
class MyClass:
a = 1
def __init__(self): ...
> class myClass
> def __init__(self):
> self.a = 1
> ...more stuff here
>
> Which is the correct idiom? or is there a subtle difference I am
> missing?
In the former corrected version, the variable a is a class variable;
that is, it's shared by all instances. In the latter, it's an instance
variable, and is specific only to one instance.
>>> class C:
... s = 1
... def __init__(self, x):
... self.x = x
...
>>> c1 = C(2)
>>> c2 = C(3)
>>> c1.x
2
>>> c2.x
3
>>> c1.s
1
>>> c2.s
1
>>> C.s = 10 # note: changing the class variable, not an instance one
>>> c1.s
10
>>> c2.s
10
--
Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
__ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE
/ \ God grant me to contend with those that understand me.
\__/ Thomas Fuller
Polly Wanna Cracka? / http://www.pollywannacracka.com/
The Internet resource for interracial relationships.
More information about the Python-list
mailing list