Is it a good programming habit to initialize class attributes while defining a class ? | Sololearn: Learn to code for FREE!
Neuer Kurs! Jeder Programmierer sollte generative KI lernen!
Kostenlose Lektion ausprobieren
+ 1

Is it a good programming habit to initialize class attributes while defining a class ?

Does this method have any particular advantages or disadvantages ? In what cases should it be done or avoided ? In most of the cases I have only seen intialization done for objects using constructors.

4th Dec 2022, 6:46 AM
Krishna Sarawagi
Krishna Sarawagi - avatar
1 Antwort
0
I think that you are mixing class attributes and instance attributes that are distinct class C: CA= 5 def __init__(self, n): self.ia= n CA is a class attribute and ia is a instance attribute. The first have to be initialized in class context because is class-owned (all instance of that class will refer to CA to the same object) while the latter is initre in ctor because is instance-owned (any instance of that class will have a different ia object). I supposed that you referring to python language but tha concept is similar to other oop languages too (with som differences in inizialitation syntax and semantic)
4th Dec 2022, 10:03 AM
KrOW
KrOW - avatar