Attributes initialization/declaration in Python class: where to place them?

PythonCoding StyleAttributes

Python Problem Overview


I was wondering what was the best practice for initializing object attributes in Python, in the body of the class or inside the __init__ function?

i.e.

class A(object):
    foo = None

vs

class A(object):
   def __init__(self):
       self.foo = None

Python Solutions


Solution 1 - Python

If you want the attribute to be shared by all instances of the class, use a class attribute:

class A(object):
    foo = None

This causes ('foo',None) to be a (key,value) pair in A.__dict__.

If you want the attribute to be customizable on a per-instance basis, use an instance attribute:

class A(object):
   def __init__(self):
       self.foo = None

This causes ('foo',None) to be a (key,value) pair in a.__dict__ where a=A() is an instance of A.

Solution 2 - Python

Attributes defined in the class definition are considered class variables (like static variables in Java), while those set in the initializer are instance attributes (note the difference between self.something = 1 and something = 1). See this question for more details, and this one for even more. There is not a lot of practical difference between these two cases, as the class-level definition gives the attribute a default value, but if you want to use some kind of logic to set an attribute before using an object instance you should do it in the __init__() method.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionfortranView Question on Stackoverflow
Solution 1 - PythonunutbuView Answer on Stackoverflow
Solution 2 - PythonandronikusView Answer on Stackoverflow