Class and Instance Attributes in Python
Last Updated :
20 Apr, 2020
Class attributes
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.
class sampleclass:
count = 0
def increase( self ):
sampleclass.count + = 1
s1 = sampleclass()
s1.increase()
print (s1.count)
s2 = sampleclass()
s2.increase()
print (s2.count)
print (sampleclass.count)
|
Output:
1
2
2
Instance Attributes
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).
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.
class emp:
def __init__( self ):
self .name = 'xyz'
self .salary = 4000
def show( self ):
print ( self .name)
print ( self .salary)
e1 = emp()
print ( "Dictionary form :" , vars (e1))
print ( dir (e1))
|
Output :
Dictionary form :{'salary': 4000, 'name': 'xyz'}
['__doc__', '__init__', '__module__', 'name', 'salary', 'show']
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...