Two passages do different things, so this is not a matter of taste, but a matter of proper behavior in your context. The Python documentation explains the difference, but here are a few examples:
Exposition A
class Foo: def __init__(self): self.num = 1
This binds num to Foo instances . Changing this field does not apply to other instances.
In this way:
>>> foo1 = Foo() >>> foo2 = Foo() >>> foo1.num = 2 >>> foo2.num 1
Illustration B
class Bar: num = 1
This binds num to the Foo class . Changes are spreading!
>>> bar1 = Bar() >>> bar2 = Bar() >>> bar1.num = 2
Actual answer
If I don't need a class variable, but only need to set a default value for my instance variables, are both methods equally good? Or is one of them more "pythonic" than the other?
The code in exponent B is not right for this: why do you want to bind a class attribute (the default value when creating an instance) to one instance?
The code in exhibitor A is fine.
If you want to specify default values ββfor instance variables in your constructor, I would do this:
class Foo: def __init__(num = None): self.num = num if num is not None else 1
... or even:
class Foo: DEFAULT_NUM = 1 def __init__(num = None): self.num = num if num is not None else DEFAULT_NUM
... or even: (preferable, but if and only if you are dealing with immutable types!)
class Foo: def __init__(num = 1): self.num = num
That way you can:
foo1 = Foo(4) foo2 = Foo()
badp Apr 21 '10 at 8:20 2010-04-21 08:20
source share