Class And Instance Attributes in Python
Object Oriented Programming (OOP) is a programming paradigm, that means: a programming model or style that gives us some guides to work with it. It is based on the concept of classes and objects. In Python everything is an object. OOP was "created" with the objetive of structure a software program into simple, reusable pieces of code, like blueprints (classes) to create individual instances of objects.
Throughout history, different programming paradigms have appeared. Sequential languages like COBOL or procedural languages like Basic or C, focused more on logic than on data. Others more modern such as Java, C # and Python, use paradigms to define the programs, being Object Oriented Programming the most popular.
With the Object Oriented Programming, what we seek is to stop focusing on the pure logic of programs, to start thinking about objects, which is the basis of OOP. This helps us a lot in large systems, since instead of thinking in functions, we think about the relationships or interactions of the different components of the system.
A programmer designs a software program by organizing pieces of information and related behaviors into a template called a class. Then individual objects are created from the class template. The entire software program runs by causing various objects to interact with each other to create a larger program.
Another way of saying it is that classes are like planes of anything, in this case objects, with their own characteristics (attributes) and actions to perform (methods).
In Python everything is an object but we will leave that for the next blog. Objects are a representation of real world objects like cars, dogs, houses, etc. Everyone shares data and behaviors. In this case, our example is with Cars.
Class Attributes
Class attributes are attributes which are owned by the class itself. They will be shared by all the instances of the class. Therefore they will have the same value for every instance. We define class attributes outside of all the methods, usually, they are placed at the top, right below the class header.
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.
Let’s add a counter to our new Car class.
class Car counter = 0 def __init__(self): Car.counter += 1 a = Car() b = Car() print(a.counter)
# 2
Instance Attributes
Instance attributes are owned by the specific instances of a class. This means for two different instances the instance attributes are usually different. Let’s give our Car class an instance attribute, “name”.
Unlike class attributes, instance attributes are not shared by objects. Every object has its own copy of the instance attribute (In case of class attributes all object refer to single copy).
class Car: counter = 0 def __init__(self, name): Car.counter += 1 self.name = name a = Car("Sedan") b = Car("Hatchback") print(a.name) # 'Sedan' print(b.name)
# 'Hatchback'
The Pythonic way
Getters and setters. This method involves placing some code for private methods/attributes and underscores ("__" at the beginning) for protected methods/attributes. The property and setter decorators (@ with the word) are also used to methods as setters/getters.
class Car: counter = 0 def __init__(self, name): Car.counter += 1 self.name = name @property def model(self): return self.__name @model.setter def name(self, name):
self.__name = name
Differences between class and instance attributes
The biggest difference between instance and class attributes are that class attributes can be declared outside of methods and exist across different instances of classes. Instance attributes, however, use setter methods to instantiate clones of the parent class. Look the image, No of Wheels, Width, Height and Name are attributes from class Car but for example Bonnet is an instance attribute from Sedan and only from Sedan.
Advantages and drawbacks
The advantage of instance attributes is that you can parse and sanitize the data the user passes in before assigning it to the instance of the class. This means you can throw errors if it doesnt fit the requirements you set before. The objects that are created also can be unique within the confines of the setter methods. Drawbacks include
__dict__
The special method dict is to check all your class attributes, you can use the special method __dict__ as the example to list them.
class Car: ... print(Car.__dict__)
# mappingproxy({'__module__': '__main__', 'counter': 0, '__init__': <function Car.__init__ at 0x10148e598>, 'name': <property object at 0x1014969a8>, '__dict__': <attribute '__dict__' of 'Car' objects>, '__weakref__': <attribute '__weakref__' of 'Car' objects>, '__doc__': None})
To list the attributes of an instance/object, we have two functions:-
1. vars()– This function displays the attribute of an instance in the form of an dictionary.
2. dir()– This function displays more attributes than vars function,as it is not limited to instance. It displays the class attributes as well. It also displays the attributes of its ancestor classes.
And thats it, thanks for be here and reading my new blog, more tomorrow with Python and everything is an object.