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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With