
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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
Example
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
- Related Articles
- What is the correct way to define global variables in JavaScript?
- What is the correct way to pass an object with a custom exception in Python?
- What is the difference between class variables and instance variables in Java?
- What is the correct way to check if String is empty in Java?
- What is the correct way of using , , or in HTML?
- What is the best way of declaring multiple Variables in JavaScript?
- Class or Static Variables in Python?
- What is the currently correct way to dynamically update plots in Jupyter/iPython?
- What are class variables, instance variables and local variables in Java?
- What is the correct way to use printf to print a size_t in C/C++?
- What is the correct way to replace matplotlib tick labels with computed values?
- What is the correct way to implement a custom popup Tkinter dialog box?
- How to define attributes of a class in Python?
- How to define variables in C#?
- What is the simplest way to SSH using Python?

Advertisements