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
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.
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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With