Reputation: 604
In Python I can refer to a class level variable with either ClassName.class_var
or self.class_var
from within a class. Now as long as I do not override the class level variables name within an object by creating an instance variable of the same name (which I find would be kind out silly), they will always refer to the same thing.
My question is, which is a better practice? or more common?
I see coding books and source code itself using either way. In some cases, I see them using BOTH methods to refer to the variable within the same class which I think is really inconsistent.
Here I provide an example :
class Foo(object) :
class_var = ['same','for','all']
def __init__(self, instance_var) :
self.instance_var = instance_var
def print_words(self) :
# here I could use self.class_var
for w in Foo.class_var :
print w
Upvotes: 11
Views: 7674
Reputation: 2228
The problem with using Foo.class_var
from your example is in inheritance. You can see it illustrated here, beginning with your Foo() class:
class Bar(Foo):
class_var = ['other','one','here']
In [2]: a = Foo(['one'])
In [3]: b = Bar(['one'])
In [4]: a.class_var
Out[4]: ['same', 'for', 'all']
In [5]: b.class_var
Out[5]: ['other', 'one', 'here']
In [6]: b.print_words()
same
for
all
It's possible this is the behavior you want, but I think it's uncommon. You're usually going to run into the self
variety.
Upvotes: 1
Reputation: 13779
If you have only the one class and you only read the variable, you won't see a lot of difference.
If you take into account the possibility of subclasses that override class_var
, then self.class_var
will look in the current class first while Foo.class_var
will continue to refer concretely to that particular value. The best practice depends on your intent but since using classes in a language that makes them optional implies at least some interest in polymorphism, self
is probably more generally useful.
Also, if you want to set the value, self.whatever =
will set an instance variable and Foo.whatever =
will set the class variable which could then affect any other instance as well.
Upvotes: 11