Class and instance attributes.
Class
Classes provide a way to package data and functionality together. When creating a new class, create a new type of object, create new instances of that type. Each class instance can have attributes attached to maintain its status. Class instances may also have methods (modified by their class) to modify their status.
Class objects.
Class objects support two types of operations: reference to attributes and instantiation.
To reference attributes, the standard syntax of all references to attributes in Python is used: object.name Valid attribute names are all names that were in the class namespace when it was created. Therefore, if the definition of the class is like this:
class MiClass:
"""Simple example class"""
i = 12345
def f(self):
return 'hello world'
…Then MiClase.i and MiClase.f are valid attribute references, which return an integer and a function object respectively.
Instance Attribute.
An instance attribute is a Python variable belonging to only one object. It is only accessible in the scope of the object and it is defined inside the constructor function of a class. For example, __init__(self,..).
instance_attr
is an instance attribute defined inside the constructor.
class MiClass(Object):
class_attr = o
def __init__(self, instance_attr):
self.instance_attr = instance_attr
Class Attribute.
A class attribute is a Python Variable that belongs to a class rather than a particular object. This is shared between all other objects of the same class and is defined outside the constructor function __init__(self,…), of the class.
class_attr
is a class attribute defined outside the constructor.
class MiClass(Object):
class_attr = o
def __init__(self, instance_attr):
self.instance_attr = instance_attr
Differences Between Class and Instance Attributes.
The difference between a class attribute and an instance attribute is found in the way of accessing them, therefore for instance attributes it is only possible to access through an object, for class attributes it is accessed directly from the class and / or also through an object.
__dict__
A __dict__
is the dictionary containing the class’s namespace, and maping objet used to store an object’s attributes. How does Python deal with the object and class attributes using the __dict__
? Well, each instance is stored in a dictonary.