- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Explain the variables inside and outside of a class __init__() function in Python.
Class variables vs Instance Variables
All variables outside the class __init__ function in Python are class variables while those inside the same are instance variables. The difference between the class variables and instance variables is understood better by examining the code below
Example
class MyClass: stat_elem = 456 def __init__(self): self.object_elem = 789 c1 = MyClass() c2 = MyClass() # Initial values of both elements >>> print c1.stat_elem, c1.object_elem 456 789 >>> print c2.stat_elem, c2.object_elem 456 789 # Let's try changing the static element MyClass.static_elem = 888 >>> print c1.stat_elem, c1.object_elem 888 789 >>> print c2.stat_elem, c2.object_elem 888 789 # Now, let's try changing the object element c1.object_elem = 777 >>> print c1.stat_elem, c1.object_elem 888 777 >>> print c2.stat_elem, c2.object_elem 888 789
Advertisements