- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What is the correct way to define class variables in Python?
Class variables are variables that are declared outside the__init__method. These are static elements, meaning, they belong to the class rather than to the class instances. These class variables are shared by all instances of that class. Example code for class variables
class MyClass: __item1 = 123 __item2 = "abc" def __init__(self): #pass or something else
You'll understand more clearly with more code −
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
- What is the proper way to define a global variable that has class scope in python?
- What is the correct way to check if String is empty in Java?
- What is the correct way to pass an object with a custom exception in Python?
- What is the currently correct way to dynamically update plots in Jupyter/iPython?
- What is the correct way to implement a custom popup Tkinter dialog box?
- What is the correct way to replace matplotlib tick labels with computed values?
- What is the correct way to use printf to print a size_t in C/C++?
- The correct way to work with HTML5 checkbox
- What is the difference between class variables and instance variables in Java?
- The correct way to trim a string in Java.
- What is correct operators precedence in Python?
- What is correct syntax to create Python tuples?
- What is correct syntax to create Python lists?