- Python Class Constants
- How Does Python Class Constants Work?
- Examples of Python Class Constants
- Example #1
- Example #2
- Example #3
- Conclusion
- Recommended Articles
- Python Constants — Everything You Need to Know
- What are Constants in Python?
- Constants in Python for Data Types
- Named Constants in Python
- Constants in Python Classes
- Conclusion
- Recommended reads
- Stay connected
Python Class Constants
An unchangeable value, assiged, is called a constant. Meaning, constants are the containers that hold some information and cannot be changed further. Write once, read many times constants are created in the class of Python. Usually, constants are defined in the level of a module. They are written in capital letters. An underscore separates each word. Though in reality, generally, the usage of class constants in Python isn’t done. Because the constants modules or global variables used are throughout the Python programs.
TOTAL, GROSS_BUDGET or assigning them like PI = 3.14
So, for the examples, creating a module file – constant.py is done.
As above mentioned, the syntax for Python class constants is something like this:
#Declaring a value to a constant PI = 3.14
A value is declared and is known for being constant, is represented by giving capital letters to any variable considered.
Objects such as dictionaries and lists are mutable, that is, changeable. If const is bound to such objects, for example, a list object, the name is always bound to the object list. The contents of the list, though, may change. Meaning, unbound or rebound of items and more items can be removed and added with the object through methods like append.
How Does Python Class Constants Work?
In a human understanding, or non-technical, the constants can be considered as something you buy and don’t have an exchange policy. Or in other words, you buy some books, take any number of books, and taking the bag as a constant, those books once placed in the bag, cannot be replaced back again.
Now, getting into the actual working:
In Python, variables are named locations that are basically used to store data within the memory. The unique Identifier name is given to each and every variable. Variables do not need the declaration prior to reserving memory. Variable initialization automatically happens after assigning a value to a variable.
count = 0 employee_name = hemanth age, agee, ageee = 22
But then, what if you want to create a global variable that is unchangeable and unique for itself?
For that, you need to declare a constant, which is pretty much the same as declaring a variable but with capital letters. Declaration of any variable with capitals considered a constant.
The Python constants are first created. These are identified to be constants as they are capitalized letters. They are given with an underscore in between to potrait it as a single variable. The variable is then assigned a value that is globally the same or consistent throughout the program. Once allocated, it is the same anytime.
Declaring a Constant in Python:
GOLDEN_RATIO = 1.62 PI = 3.14
And then, in the main, you import the constant module.
main.py is created later:
import constant print(constant.GOLDEN_RATIO) print(constant.PI)
Examples of Python Class Constants
- Always declare a constant by capitalizing on the letters.
- Nomenclature is always a purpose.
- Python modules have constants put into Python modules and are meant not to be changed.
- Use underscores when you need them.
- Underscores makes the code pretty neat and readable. A word is neat and understandable than a letter. Let’s say you want to declare a variable number of case studies as a constant. You will realize that declaring it as CASE_STUDY is much more of a tip-off than saying it CS or C.
- You cannot start a constant variable with a digit.
- You cannot use special symbols like @, #, &, %, $ etc.
- You can always access the class constants from a superclass to a subclass.
Example #1
NAME = 'hemanth' YOB = 1999 ID_NUM = 17783 print(NAME)
Example #2
NUM1 = 50 num2 = 65 print(num2+NUM1)
Accessing class constants from a subclass in a Python:
self.a_constant is used when you need to access any class constant that was defined previously in the superclass. An example will make a better understanding:
Example #3
#access class constants from superclass to subclass class C1: A_CONSTANT = 0.167355 class C2(C1): def this_constant(self): print(self.A_CONSTANT) an_object = C2() an_object.this_constant()
Conclusion
Other programming languages like C++ and Java does not provide this type of constants, unlike Python. Writing a variable in upper case letters, may it be any variable, is considered and termed a constant. String, Tuples, and Numbers are immutable. Binding a name with const to tuples, strings, and numbers, the name is always is bound to the object. And also, the content of the object’s will also always be the same because the object is immutable.
Recommended Articles
We hope that this EDUCBA information on “Python Class Constants” was beneficial to you. You can view EDUCBA’s recommended articles for more information.
Python Constants — Everything You Need to Know
Python Constants contribute to the dynamic and updatable characteristic of the design architecture, which is essential for any coding architecture. Providing a construction with these features is related to the fact that the code blocks can be understood and developed by someone else.
To meet those versatile conditions, the expressions in code should be clear, unambiguous, and uncomplicated. Programming languages have many useful expressions to provide these kinds of flexibilities. In this article — Constants — one of them, is analyzed in detail and supported by coding implementations in Python.
What are Constants in Python?
Constants are one of the building blocks of programming languages and one of the facilities that provide the necessary flexibility for users. As the name implies, constants are units that allow users to assign values that cannot be edited after they are defined.
The tricky point here is that although a constant cannot be edited, it can be updated. On the other hand, there are cases where constants are mutable and these are discussed in detail with examples in the next section. A Python example of a case where constants are immutable is as follows:
It is intended to change the first letter of the word “Python” assigned to the VALUE “Xython”, but it is impossible to change it. VALUE is defined as a constant and cannot be edited. When the code block above runs, the error, “TypeError: ‘str’ object does not support item assignment.”, occurs. If we want to get the word “Xython”, we need to assign it to a new value just like VALUE which we defined the word “Python”. It is also possible to update the constant “Python” to “Xython” by assigning it to VALUE .
The facilitating effect of constants on the models developed is also undeniable. A certain number, text, list, or tuple can be used in more than one place in the program.
For example, let’s imagine that we will import more than one dataset from different links locally or over the Internet. In this case, in each operation, this link must be introduced separately to the command to be re-imported. However, if this link is assigned to a certain constant, and this expression is written where the link is needed in the run, it will be sufficient to change only this assigned link instead of changing the data in the entire code block one by one. It will also make the code system more understandable and easier to manage.
Constants are usually assigned to expressions consisting of capital letters, of course, they are not mandatory, but they are like a kind of culture developed by developers over time.
Similarly, values such as “int” or “float”, like “str” values, can be assigned to certain constants, making the construction of the coding model more efficient. For example, parameters such as image width and image height used in image processing appear in more than one place in the work. When these expressions are assigned to IMAGE_WIDTH and IMAGE_HEIGHT as constants at the beginning of the run, changing only the values at the beginning of the code block will save changing the entire structure and would provide convenience.
In C programming language, when assigning data, it is defined by adding expressions such as “int”, that is, integer, which determines the data type. Python, on the other hand, provides convenience in this case and assigns the data type itself. For example:
X = 22 print(type(X)) Y = 22.22 print(type(Y)) VALUE = "Python" print(type(VALUE))
When the type of constants is examined by running the above code block, the output is:
Although not specified by the user, it assigned the number 22 as an integer, 22.22 as float, and the word “Python” as a string. Of course, these types can also be assigned by the user as follows:
X = float(22) print(type(X)) Y = str(22.22) print(type(Y)) print("Length of Y:", len(Y))
When the float value 22.22 is defined as a string, each object is defined as an element. Since there are 4 “2” values and 1 “.”, the length value is 5:
Constants in Python for Data Types
There are 2 types of objects: mutable — objects that can be modified (edited) after they are created, and immutable — objects that cannot be modified (edited) after they are created.
Python data types where constants are mutable:
A simple list object type is constructed and observed to be modified as follows:
CONTINENTS = ["Asia", "Europe", "Africa"] print(CONTINENTS) CONTINENTS[1] = "Antartica" print(CONTINENTS) print(type(CONTINENTS))
The output of the above code block is:
Changing Europe to Antarctica in the CONTINENTS list was a success. Since the Python list object is mutable, Python performed the operation without any error.
Python data types where constants are immutable:
The above error message occurred when int, float, and string types are changed. The same is done below for the tuple type:
The value “2”, the second element of the tuple type constant defined as X , wanted to be replaced with “25”. Outputs are as follows:
What needs to be done here is to redefine X = (1, 25, 3) to avoid this sort of error.
Named Constants in Python
A named tuple structure is a class type that maps the given values under the collections module. The constants assigned with this mapping process can be easily passed through the prepared operations.
With a more concrete example: Let’s assume that the weight of the quiz in a class is 30% and the final exam is 70% and calculate the average of the students using namedtuple :
from collections import namedtuple Grade = namedtuple('Grade', 'quiz final_exam') student_1 = Grade(60.0, 75.0) student_2 = Grade(60.0, 90.0) def average_grade(student_ID): student_ID_average = (student_ID.quiz) * 0.3 + (student_ID.final_exam) * 0.7 return student_ID_average student_1_average = average_grade(student_1) student_2_average = average_grade(student_2)
Grade is assigned quiz and final_exam results through mapping with namedtuple. After these results are retrieved by the user in student_1 , student_2 format, the average_grade function is created as above. As a result, the average grade was calculated with the quiz exam weighted 30% and the final exam weighted 70%.
Constants in Python Classes
There are 2 types of constants in the coding structure: local constants and global constants. If constants are defined outside the class and def block, they are called global constants, if they are defined inside, they are called local constants. To call a constant in a class in another class:
class Value: constant_f = 30.05 constant_s = "Hello World" class FinalValue(Value): def const(self): print("float constant is:", self.constant_f, "\n","string constant is:", self.constant_s) value_in_class = FinalValue() value_in_class.const()
constant_f is assigned a float value of 30.05 and constant_s is assigned a string value of “Hello World”. The above code block is used to call this in the FinalValue class. The output is:
Conclusion
The constant structure has a very important place not only in Python but in all programming languages. It makes the constructed system more understandable and makes the work easier.
Since Python is a user-friendly programming language in terms of syntax, it provides a very favorable environment for the use of constants. Operations that can be done with longer code blocks can be done with less workload with the understanding of constants.
What’s your take on constants in Python? Let me know in the comment section below.