Change language

Class and instance attributes in Python

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

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News


Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method