How object and class attributes work ? (Python)

--

Object-Oriented Programming(OOP). Perhaps defining this concept is the best way to start this blog. OOP is basically one way of programming usually implemented in high-level languages; another type is procedural programming. Another manner of seeing OOP, and actually it’s how I picture it, is like giving life to the objects that surround you and me, and being able to create, modify and delete them whenever you want. Python accepts both of these types. Classes and objects are used when using this type of programming, this is way it was important to define this first.

Now we can define what a class attribute is. This kind of attribute is a characteristic that defines the class, not directly the object. It is not defined in the constructor method (__init__), since the class attribute refers only to the attributes defined in the class. On the other hand, there’s another type of attribute named: Instance attribute. This attribute belongs only to one object, that’s why it receives that name; and it is defined inside of the constructor.

To understand better their concept and how they created I have created an example:

class ExampleClass():  class_attr = 0  def __init__(self, instance_attr):    self.instance_attr = instance_attr

Differences

As mentioned already, one difference between these attributes is where they are defined. The class attribute is defined outside of the constructor, and the instance attribute is defined inside. Another difference is that the class attribute is shared by all instances. The instance attribute is unique to that instance only. For last, it’s important to highlight the fact that if you change a class attribute it will override all of the instances (objects) created.

Advantages and drawbacks of attributes

Class attributes are used when you need to define a set of characteristics throughout all the instances, something all of them have in common. So, its main use is observed when you set a kind of template of a set of objects that have something in common. An instance attribute is extremely specific to an object, and if the class attribute is modified it will be overridden no matter what.

I hope this blog helps you out, I’m a constant learner of this technology, and I’m inspired of what it can be accomplished with it, so my duty is to try to help out all of those who like me, needs help when desiring to understand this kind of topics. This blog is made to help out as much as I can, thank you for your time and I really hope it made your life a little easier.

--

--