Classes in Python
A class is a container in which you can put variables, arrays, functions, etc.. To
define a new class, we write class, then put a name for it, and then put a colon.
In the following example, we created a class namedMyClass,We put a variable in itx.
Example
class MyClass: x = 3
object in python
The object is a copy of the class.
To create an instance of a class, we define a variable whose value is equal to the name of the class, and then we put parentheses.
In the following example, we created a class namedMyClass,We put a variable in itx.Then we created an object from this class calledobj.
Example
# MyClass Here we have defined a class named
class MyClass:
x = 0
# obj named MyClass Here we have created an object from the class
obj = MyClass()
# obj in object x here we have changed the value of the variable
obj.x = 10
# obj located in object x here we have shown the value of the variable
print('obj.x =', obj.x)
• We will get the following result when running.
Features in Python
Any variable that you define directly in the class is called a property( Property).
This is because each instance of the class you create will have its own copy of this variable.
In the following example, we created a class namedMyClass,We put a variable in itx.
Then we created two objects of this class named o1ando2.
Example
# MyClass Here we have defined a class named
class MyClass:
x = 0
# o2 and the second one is o1 the first is his name, MyClass here we created two objects from the class
o1 = MyClass()
o2 = MyClass()
# o2 in object x and the value of o1 in object x here we made we changed the value of
o1.x = 10
o2.x = 20
# o2 in object x and the value of o1 in object x here we have shown the value of the variable
print('o1.x =', o1.x)
print('o2.x =', o2.x)
• We will get the following result when running.
o2.x = 20
• We notice that every object we create from the class MyClasshas its own copy of the variablex.
word selfin python
When defining a function inside a class, Python forces you to put the word selfor any other word as the first parameter in it and then put the number of parameters you want.
So, even if you don't intend to put any parameter in the function, you are forced to put the word selfor any other word as a parameter in it.
advice
Since most programmers put a word as the selffirst parameter in the function, it is better to use this word as well so that it works in the same way that most programmers work around the world.
Put the word as the selffirst parameter in the function
Putting the word as the selffirst parameter in the function makes the Python interpreter able to access the properties of the same class. That is, when you put this word as a parameter in the function, this word becomes a pointer to the class itself, which makes you able to access anything that was defined inside the class through it.
In the following example, we created a class namedComparator,We put in it a function whose name print_maxis only two parameters( aand b).
Note that we are forced to put the word as the selffirst parameter in the function even if we don't need it and when we call the function we don't pay attention to it.
first example
# Salary Here we have defined a class named
class Comparator:
# then prints the largest value between them .b and a here we have defined a function that takes two values when called and stores them in the two parameters
def print_max(self, a, b):
if a > b:
print(a, 'is bigger')
elif a < b:
print(b, 'is bigger')
else:
print('They are equal')
# comparator named Comparator Here we have created an object from the class
comparator = Comparator()
# and pass two values to it to print the value of the largest number between them print_max() Here we called the function
comparator.print_max(2, 6)
• We will get the following result when running.
In the following example, we created a class whose name Salarycontains special functions to print the employee's salary without deduction and after deduction of taxes.
The salary will be stored in a variable namedvalue.
The function that prints the salary as we have named itprint_salary.
We named the function that prints salary after taxes are deductedprint_net_salary.
Note: When the function is called print_net_salary(), we pass a number representing the tax percentage in percent, on the basis of which the net salary will be calculated and printed.
second example
# Salary Here we have defined a class named
class Salary:
# This variable will be stored in the salary
value = 0
# as it is ( value and its task is to print the salary ( ie the value of the variable - self here we have defined a function in which there is no parameter - except for the word
def print_salary(self):
print('Salary:', self.value)
# Its task is to print the salary after deducting the tax rate from it - self. Here we have defined a function in which there is one parameter - in addition to the word
# rate_percentage We will put in it temporarily the amount that will be deducted according to the rate of tax that will be passed in place of the variable rate parameter
def print_net_salary(self, rate_percentage):
rate = self.value / rate_percentage
print('Net Salary:', self.value-rate)
# salary named Salary. Here we have created an object from the class
salary = Salary()
# salary in the salary object here we have changed the value of the variable
salary.value = 1500
# To print the salary as it is print_salary() here we called the function
salary.print_salary()
# To print the value of the salary after deducting 10% of it print_net_salary() Here we called the function
salary.print_net_salary(10)
• We will get the following result when running.
Net Salary: 1350.0
function __init__()in python
In the beginning, every class in Python or you create it yourself, has a set of ready-made functions, the most important of which is the function__init__().
This function enables the programmer to pass values to an object's properties directly when it is created.
A while ago we said that when creating an object from any class, we write the name of the class and then put parentheses.
Now you need to know that you can pass property values directly between these parentheses as long as you have the class configured for this.
Handling the function__init__()
First you have to define this function just like any function you define.
In the parentheses of the function, you can directly pass the names of the properties that you want to put in the class and that you want to give initial values directly when creating objects from the class.
In the following example, we created a class namedPerson,It contains a function whose name __init__()is only parametrin( nameand age),So when creating an object from this class, these two parameters will become properties of that object.
Then we defined a function named print_info()in the class interested in Persondisplaying the values of these two parameters.
Example
# Salary Here we have defined a class named
class Person:
# ( age and name ) and we put two parameters in it __init__() here we have defined the function
# __init__() because they are set as parameters in the Person function they will be set as properties in the age and name classes Remember that
def __init__(self, name, age):
self.name = name
self.age = age
# in an orderly Person whose task is to print the values of the class properties print_info() Here we have defined a function named
def print_info(self):
print('Name:', self.name)
print('Age:', self.age)
print('-----------------')
# p2 and the second name is p1 the first is named Person, here we created two objects from the class
p1 = Person('Ahmad', 24)
p2 = Person('Maria', 19)
# So that the values of their properties are printed in order p2 and p1 from the two objects print_info() here we called the function
p1.print_info()
p2.print_info()
• We will get the following result when running.
Age: 24
-----------------
Name: Maria
Age: 19
-----------------
The relationship between the class and the object in Python
The basic idea of the class is to prepare the general form of data storage and provide easy-to-use ways to access this data and deal with it smoothly.
So the class, by its nature, does not preserve any information, which is why it is called a raw copy(Blue Print).
The basic idea of the object is to create an exact copy of the class and enter the data you want in it while respecting any conditions placed in the main class.
So it is not possible to create an object without a class because the object is by nature copies of a specific class.
The benefit of the class
The properties that each object must have, are defined only once in the main class and not for each object separately.
If you want to add, delete or modify properties of objects, we only modify in the base class because the objects are an exact copy of the class.
Classes can be placed in a special file, and this will help you a lot in the future when arranging the project code - which may consist of dozens of classes - in an easy way to review and develop.
The ability to group objects and move them at once, whether to store them in a database or to transfer them between one screen and another, etc..
These things we will explain in detail at an advanced level.
Now, if you intend to create a simple program to save the information of an unlimited number of people. Each person has a name, gender, age and occupation. What are you going to do?!
Simply the solution is to create only one class that represents a person, and put in it the basic things that you want to be present in each person. Then you create as many objects from it as you want, and then each object of this class becomes a person with its own information, as in the following picture.
As you can see, we have created a class containing the basic information that we want to fill in for each person.
Then we created 4 objects (ie 4 people), and then we entered private information for each object in them.
Now if you add any new variable or function in the class Person, any object of this class will have a copy of the new thing you added.
And if you modify a specific code in the class Person, this code will also be modified for all objects of this class.
Example
Now we will create the class Personand then create 4 objects from it.
Note: We will put the class Personin a file(any module)Special and then we will include it in the program for the sake of arranging the code only.
Example
# Person Here we have defined a class named
class Person:
# As a default value None and we gave them ( age , job , gender , name ) and put 4 parameters __init__() here we have defined the function
# __init__() because they are set as parameters in the Person function they will be set as properties in the classes age, gender, job and name Remember that
def __init__(self, name=None, gender=None, job=None, age=None):
self.name = name
self.gender = gender
self.job = job
self.age = age
# in an orderly Person whose task is to print the values of the class properties print_info() Here we have defined a function named
def print_info(self):
print('Name:', self.name)
print('Gender:', self.gender)
print('Job:', self.job)
print('Age:', self.age)
print('-----------------')
# Person in the Person module Here we have included the class
from Person import Person
# With the values of their default attributes p4 and p3, p2 and p1 replaced with their name Person here we created 4 class objects
p1 = Person('Mhamad', 'Male', 'Programmer', 21)
p2 = Person('Rose', 'Female', 'Secretary', 22)
p3 = Person('Ahmad', 'Male', 'Doctor', 34)
p4 = Person('Rabih', 'Male', 'Engineer', 27)
# To print their properties values in order p4, p3, p2, p1 from print_info() objects here we called the function
p1.print_info()
p2.print_info()
p3.print_info()
p4.print_info()
• We will get the following result when the module is turned ontest.
Gender: Male
Job: Programmer
Age: 21
-----------------
Name: Rose
Gender: Female
Job: Secretary
Age: 22
--------- --------
Name: Ahmad
Gender: Male
Job: Doctor
Age: 34
-----------------
Name: Rabih
Gender: Male
Job: Engineer
Age: 27
- ----------------