Class and instance attributes
In Python, you can group a class into data and create a new object type. Each instance can have attached attributes and can be used for content creation.
Class Attribute
An instance attribute is a Python variable belonging to one, and only one, object. This variable is only accessible in the scope of this object and it is defined inside the constructor function, __init__(self,..) of the class.
>>> class A:
... a = "I am a class attribute!"
...
>>> x = A()
>>> y = A()
>>> x.a
'I am a class attribute!'
>>> y.a
'I am a class attribute!'
>>> A.a
'I am a class attribute!'
>>>
Instance Attribute
A class attribute is a Python variable that belongs to a class rather than a particular object. It is shared between all the objects of this class and it is defined outside the constructor function, __init__(self,…), of the class.
# Python program to demonstrate
# instance attributes.class emp:
def __init__(self):
self.name = 'xyz'
self.salary = 4000 def show(self):
print self.name
print self.salarye1 = emp()
print "Dictionary form :", vars(e1)
print dir(e1)
Differences Between Class and Instance Attributes
Only one object is referred to in the case of a class attribute, while there may be multiple objects in the case of a set of instance attributes in the installation.
__dict__
A __dict__ is a dictionary or 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.
The Pythonic way
class TestClass:
instances = 0
def __init__(self, name):
TestClass.instances += 1
self.name = name
@property
def name(self):
return self.__name
@name.setter
def name(self, name):
self.__name = name