1

I want to know which one is the best way to access the class variable in a class, either by self, or by class name

I have read somewhere that self is only used for accessing the instance variable. But when I tried with the below code, it is one of the same things. Is is it mean that we can use either of them?

class MyClass:
    cls_var = 0 # class variable

    def increment(self, incre):
        self.cls_var += incre
        MyClass.cls_var += incre

    def print_var(self):
        print(self.cls_var) #Choice 1
        print(MyClass.cls_var) # Choice 2


obj1 = MyClass()
obj2 = MyClass()

obj1.increment(5)
obj2.increment(10)

obj1.print_var() #prints 5, 15
obj2.print_var() # prints 15, 15
2
  • Depends on what you want, a class variable can be inherited (and overwritten). So in that sense it is better to access it through self if you want to be able to alter it in a child class. Commented Jan 27, 2018 at 13:13
  • It prints 5, 15, 15, 15. can someone explain how we get this result please? Commented Jan 27, 2018 at 14:57

2 Answers 2

1

You should access a class variable only by class name, since that variable is shared among all classes. Thus, to avoid confusion, one should only access class variables by the name of the class; otherwise it might lead to surprising errors (See the second snippet).

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

Comments

0

In my opinion you should use "Choice 2", as the class variable "cls_var" is shared by all instances. So if you do

ob1.increment(5)

also "ob2.cls_var" gets incremented, but Zen of Python sais that explicit is better than implicit! So do

MyClass.increment(5)

See: https://docs.python.org/2/tutorial/classes.html#class-and-instance-variables.

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.