Skip to content

Python class constant

  • by

There is no true class constant in Python. You can simply define a class attribute and use uppercase letters with underscores separating words.

Class constants will use if you need to define some constant data within a class. Create class constants by defining class attributes with a value that should not be modified during the lifetime of the program.

Python class constant example

Simple example code.

class MyClass:
MY_CONSTANT = 10

def __init__(self, value):
self.value = value


my_object = MyClass(20)
print(my_object.value)
print(MyClass.MY_CONSTANT)

Output:

Python class constant

Comment if you have any doubts or suggestions on this Pytohn constant topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *