How should I declare default values for instance variables in Python?
Posted
by int3
on Stack Overflow
See other posts from Stack Overflow
or by int3
Published on 2010-04-21T08:11:40Z
Indexed on
2010/04/21
8:13 UTC
Read the original article
Hit count: 237
Should I give my class members default values like this:
class Foo:
num = 1
or like this?
class Foo:
def __init__(self):
self.num = 1
In this question I discovered that in both cases,
bar = Foo()
bar.num += 1
is a well-defined operation.
I understand that the first method will give me a class variable while the second one will not. However, if I do not require a class variable, but only need to set a default value for my instance variables, are both methods equally good? Or one of them more 'pythonic' than the other?
One thing I've noticed is that in the Django tutorial, they use the second method to declare Models. Personally I think the second method is more elegant, but I'd like to know what the 'standard' way is.
© Stack Overflow or respective owner