OOP basics: Class Vs Instance attributes in Python3

OOP basics: Class Vs Instance attributes in Python3Farruh AkhrorovBlockedUnblockFollowFollowingMay 28OOP in Python3Definition of attributesIn Object-oriented programming(OOP), classes and objects have attributes.

Attributes are data stored inside a class or instance and represent the state or quality of the class or instance.

In short, attributes store information about the instance.

Also, attributes should not be confused with class functions also known as methods.

One can think of attributes as noun or adjective, while methods are the verb of the class.

Class attributesThese attributes belong to the class itself, you can call them class variables.

Example:class NewClass: """Docstring""" attribute = "This is an attribute of a class"In the above snippet, attributeis a class attribute and you can access using:NewClass.

attributeorobject = NewClass()object.

attributeThey both will print “This is an attribute of a class”.

No matter how many times you create instances of the class, they will all have a copy ofattribute .

Remember, it will be copied not shared:>>> class NewClass:.

"""Docstring""".

attribute = "This is an attribute of a class".

>>> object = NewClass()>>> object.

attribute'This is an attribute of a class'>>> object.

attribute = "Changed the value">>> object.

attribute'Changed the value'>>> NewClass.

attribute'This is an attribute of a class'As you can see on the example, even though we are changing the variable via the instance to Changed the value string, when you access it using the class name NewClass.

attribute the value has not been changedInstance attributesInstances or objects can have their own attributes.

The easiest way to create an instance attribute is just assigning a new value to a new variable using instance name and .

 :>>> object.

variable = "Instance attribute">>> object.

variable'Instance attribute'>>> NewClass.

variableTraceback (most recent call last): File "<stdin>", line 1, in <module>AttributeError: type object 'NewClass' has no attribute 'variable'The new instance attribute will be created, but you cannot access it using the class name, AttributeError will be thrown as an error.

Difference between class and instance attributesBoth class and instance attribute differences can be explained using __dict__ attribute and the term namespace.

A namespace is a mapping from names to objects, with the property that there is zero relation between names in different namespaces.

They’re usually implemented as Python dictionaries.

Python classes and instances of classes each have their own distinct namespaces.

When you try to access an attribute, python will loop for that attribute inside local namespace:>>> object = NewClass()>>> object.

__dict__{}>>> object.

attribute'This is an attribute of a class'As you can see here, the local namespace is empty, but still, it's printing attibute variable because python interpreter will search for that attribute one in a parent class and so on.

This means that local namespace will take precedence and you can overwrite class attributes:>>> object.

attribute = "New value">>> object.

__dict__{'attribute': 'New value'}>>> object.

attribute'New value'>>> object.

__class__.

attribute'This is an attribute of a class'>>> object.

__class__.

__dict__mappingproxy({'__dict__': <attribute '__dict__' of 'NewClass' objects>, '__module__': '__main__', 'attribute': 'This is an attribute of a class', '__weakref__': <attribute '__weakref__' of 'NewClass' objects>, '__doc__': 'Docstring'})In this example, we are creating a variable called attribute which belongs to object but have the same name as the class attribute.

Using __class__ you can still have access to class attributes.

Advantages of class and instance attributesClass attributes are mainly used to store information which is relevant across all instances.

>>> class Animal:.

number = 0.

def __init__(self, name):.

self.

name = name.

type(self).

number += 1.

>>> dog = Animal("Rex")>>> dog.

number1>>> cat = Animal("Kitty")>>> cat.

number2>>> dog.

number2>>> Animal.

number2In this example, number class attribute will act as a global counter which will count the number of instances of the Animal class.

The benefit is you will know how many instances have been created by accessing number from any instance.

While class attributes act as a global shared variable, instance attributes will store data about a specific instance, be it breed, fur color or name in case of dog instance, which is unique to each instance.

.

. More details

Leave a Reply