Class and instance attributes in Python

Python Methods and Functions

# Write Python code here

class sampleclass:

count = 0   # class attribute

 

def increase ( self ):

sampleclass.count + = 1

 
# IN Calling increment () for object

s1 = sampleclass ()

s1.increase () 

print s1.count

 
# The call will increase by one more
# object

s2 = sampleclass ()

s2.increase ()

print s2.count

 

print sampleclass.count

Output:

 1 2 2 

Instance Attributes

Unlike class attributes, instance attributes are not I am common to objects. Each object has its own copy of an instance attribute (in the case of class attributes, all objects refer to one copy).

To list the attributes of an instance / object, we have two functions:
1.vars () — this function displays an instance attribute as a dictionary. 
2.dir () — this function displays more attributes than the vars function because it is not instance limited. It also renders class attributes.

# 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 . salary

 

e1 = emp ()

print "Dictionary form:" , vars ( e1)

print dir (e1)

Output:

 Dictionary form: {'salary': 4000,' name': 'xyz'} [' __doc__', '__init__',' __module__', 'name',' salary', ' show'] 

This article courtesy of Severe Valech ... If you are as Python.Engineering and would like to contribute, you can also write an article using contribute.python.engineering or by posting an article contribute @ python.engineering. See my article appearing on the Python.Engineering homepage and help other geeks.

Please post comments if you find anything wrong or if you'd like to share more information on the topic discussed above.





Tutorials