Python - Dont Use Static or Class variables with Self

July 03, 2018

While doing code review of one of junior, I encountered following code:

class Test:
  logger = MyLogger.get_instance()
  def __init__(self):
    client = Jira.get_instance()
				
  def do_process(self):
    self.logger.info('Hey test')
				
  # some other code

What bothered me was

  • You have used class variable, and used it with self

*What was the need of declaring it to be class variable

Buggy Part

Lets consider below code:

class Test:
  a = 20
  def __init__(self):
    self.a = 10

test = Test()
print(test.a)

test.a = 10
Test.a = 30
print(test.a)
print(Test.a)
### Output
10
10
30

What are Static or Class variables

These are the variables that are associated with class not with the instance of class. Which means, static or class variables are shared across all instances of the class. There can be an instance variable with the same name as static one. But, both will have a different identifier and can have different values.

The Best practice

Now, you should always refer class or static variable with class name. Although, you can also refere a static variable with class instance. But, it will result into nighmares of your debug life if you declare same name instance variable. Also, if some new developer joins your team and try to read your code. If you have not refered class or static variable with class name, he might consider it an instance variable which it is not.

Always refere statics like:

Test.a

Similar Posts

Latest Posts