Class initialization

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sun Aug 8 20:17:32 EDT 2010


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



More information about the Python-list mailing list