Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 
like image 991
fortran Avatar asked Oct 18 '11 15:10

fortran


People also ask

How do you initialize attributes in Python?

Use the __init__() method to initialize the object's attributes. The __init__() doesn't create an object but is automatically called after the object is created.

Where do I declare class variables in Python?

A class variable is declared inside of class, but outside of any instance method or __init__() method. By convention, typically it is placed right below the class header and before the constructor method and other methods.

How do I add attributes to a class in Python?

Adding attributes to a Python class is very straight forward, you just use the '. ' operator after an instance of the class with whatever arbitrary name you want the attribute to be called, followed by its value.

Where and how should be class attributes created Python?

Class attributes belong to the class itself they will be shared by all the instances. Such attributes are defined in the class body parts usually at the top, for legibility. Unlike class attributes, instance attributes are not shared by objects.


1 Answers

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.

like image 180
unutbu Avatar answered Sep 19 '22 18:09

unutbu