12

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

2 Answers 2

12

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.