How object and class attributes work

Fesus Rocuts
2 min readMay 28, 2019

--

What’s a class attribute

Attributes that apply to the whole class are defined first, and are called class attributes.…

What’s an instance attribute

Attributes that apply to a specific instance of a class (an object) are called instance attributes, good practice is defined inside __init__().…

What are all the ways to create them and what is the Pythonic way of doing it

What are the differences between class and instance attributes

An instance attribute: a variable belonging to only one object, besides is only accessible in the scope of this object and initialize in special function __init__(self,parameters…) of the class

A class attribute: a variable belonging to only class, besides is accessible by other objects, is defined outside special function __init__(self,parameters…) of the class, and usually typed before all methods.

What are the advantages and drawbacks of each of them

When create a new Class, you need defined if this instance should take a specific behavior, example, you think in a fruit, this have some characteristics instinctive as the flavor, the colors, the size and others, rather, you can choose your instance with this specifications.
If you need create a new object with certain characteristics and not change them, these you should use an instance attribute, also adding private access, otherwise is useful work a class attribute.

How does Python deal with the object and class attributes using the __dict__

Are data descriptors for instance variables that will hold attributes which describe them. It maps the attribute name to its value.

--

--

No responses yet