Python programming language is one of the object-oriented languages that supports all the features of object-oriented languages, so it is easy to create and use classes and objects in this programming language.
Before addressing the topic of class definition in Python, you need to know about object-oriented programming language so that it is easy for you to understand.
Object-oriented programming (OOP), unlike procedural programming that focuses on sequential and explicit instructions, focuses on creating reusable patterns. That is, object-oriented programming when working on complex applications. The author allows you to reuse the code and write code that is more readable.
The concept of class in Python programming
One of the most important concepts in object-oriented programming is the distinction between classes and objects, which is defined as follows:
In object-oriented programming, a class is a set of data (variables or attributes) and functions or methods that are members of a class.
Class data refers to variables that are input information stored in a class that attributes must be considered for each data in the class. In-class functions are called class methods that determine class behavior.
Input data is first stored in class variables and then used by class methods. In fact, using the class definition, you can find the number of objects needed in the class.
The object is an example of a class that can be used, and the relationship between the object and the class is the same as the relationship between the house and the map, and as it is clear, using the drawn map, the house can be built and lived in. So any property that has a class will have an object or instance of it.
Attributes
Compared to other object-oriented programming languages, the class structure in Python is a combination of the mechanisms found in C ++ and Modula. The class offers all the standard features of object-oriented programming, including:
- The inheritance mechanism is possible using several basic classes.
- An derived class can call each of its base classes by the same name.
- Available objects can contain arbitrary values and data types.
- As with modules, classes can take advantage of the dynamic nature of Python, meaning that they are created at runtime and can be modified after creation.
- Defined by the class keyword.
- Each code is written in indentation.
Class Definition in Python programming
As mentioned in the previous section, to define, you must first use the keyword class, then choose a name for your class, and finally write a two-dot operator. So the general rule is as follows:
1
2
3
4
5
|
Class MyClass
Statement 1
Statement 2
Statement 3
Statement n
|
As you can see in the above command, the code inside the class in Python is written with respect to the indentation relative to the first line of code.
Definition of behavior in Python programming
To define behavior within a class in Python, you must create a function inside but with a name other than init, for example, a function called fullname that displays the firstname and lastname values together.
1
2
3
4
5
6
7
8
|
class Person:
def __init__(self, firstname, lastname, age):
self.firstname = firstname
self.lastname = lastname
self.age = age
def fullname(self):
return self.firstname + ” “ + self.lastname
|
In the above code, a function called fullname is created that has no input parameter. In fact, here the self parameter is set by the interpreter and has an object on which the function is called. In the code below, you can see that we have used the fullname function.
1
2
3
|
>>> person = Person(“Hossein”,“Ahmadi”,30)
>>> print(person.fullname())
Hossein Ahmadi
|
By executing the above code, Hossein Ahmadi is displayed in the output.
Existing objects
To define objects in a class in Python, you need to know that an object is an instance of a class. A class is like a plot, while an object is an instance of a plot with real values. An object contains the following:
state of:
The state of an object is displayed by the properties of that object and also reflects the properties of an object.
Behavior:
The behavior of an object is represented by the methods of that object and also represents the reaction of an object with other objects.
Identity:
A unique name is given to an object and enables an object to communicate with other objects.
How to build an object
To access members of a class, they must be accessed through an object. After creating a class, you must first create an instance of the class in Python. As you are aware, an instance of a class is called an object, which is actually an instance variable of the corresponding class.
The first thing to do after creating a class is to create a instance of the class. As you are aware, an instance of a class is called an object, which is actually an instance variable of the corresponding class.
In the Python programming language, all variables that are created from standard Python variants are instances of a class in Python. The following code snippet creates class variables that make up the most common data types in Python.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
integer_variable = int ()
Print type(integer_variable)
float_variable = float ()
Print type(float_variable)
string_variable = float ()
Print type(string_variable)
list_variable = float ()
Print type(list_variable)
dictionary_variable = float ()
Print type(dictionary_variable)
|
To use it, you must first create an object of that class before doing anything. The following code shows how to create a class object in Python.
1
2
3
4
5
6
7
8
9
10
|
Class MyClass:
Statement 1
Statement 2
Statement 3
…
Statement n
#object 1
Obj1 = ClassName()
#object 2
Obj2 = ClassName()
|
The following code is an example of defining a class in Python:
1
2
3
4
5
6
7
8
9
10
11
12
|
class Employee:
‘Common base class for all employees’
empCount = 0
def __init__(self, nam e, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print “Total Employee %d” % Employee.em
pCount
def displayEmployee(self):
print “Name : “, self.name, “, Salary: “, self.salary
|
The concept of empCount
Is a class variable that is common to all instances of the class and can be accessed from inside and outside the class. The __init__ method is a special method called the class constructor or the initial value of the class giver, and whenever a new object of a class is created in Python, Python calls these methods.
Other methods can be defined as functions, except that the first parameter must be self, but when calling methods, Python itself creates the self parameter and does not need to be set by the programmer.
As you know, to create an object from a class in Python, it can be called using the class name, and its argon can be set to values defined by the __init__ method.
1
2
3
4
|
“This would create first object of Employee class”
emp1 = Employee(“Zara”, 2000)
“This would create second object of Em ployee class”
emp2 = Employee(“Manni”, 5000)
|
Use the phrase pass
The pass in the class definition in Python is actually the Null operator, which does not happen when the program code is executed. In fact, when we want to define a class by its name and then its commands and body, we have to use the phrase pass. Consider the following example:
1
2
3
4
5
6
7
8
|
class SampleClass1:
pass
class SampleClass2:
pass
sample1 = SampleClass1()
sample2 = SampleClass2()
|
sample1 and sample2 are both examples of the SampleClass1 and SampleClass2 classes, respectively, but since the body body of the class is not yet defined, both objects have no content.
Difference between sample variables and class variables in Python
Sample variables for data are unique to each instance, but class variables are for the attributes and methods that are shared by all class instances in Python.
In fact, sample variables are variables whose value is assigned inside a constructor or method, while class variables are variables whose value is assigned to a class. Note the following code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
class Dog:
kind = ‘canine’ # class variable shared by all instances
def __init__(self, name):
self.name = name # instance variable unique to each instance
>>> d = Dog(‘Fido’)
>>> e = Dog(‘Buddy’)
>>> d.kind # shared by all dogs
‘canine’
>>> e.kind # shared by all dogs
‘canine’
>>> d.name # unique to d
‘Fido’
>>> e.name # unique to e
‘Buddy’
|
As discussed in one word about names and objects, shared data can have amazing effects by inserting variable objects such as lists and dictionaries. For example, the list of tricks in the following code should not be used as a class variable in Python because only a single list is shared by all Dog items:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
class Dog:
tricks = [] # mistaken use of a class variable
def __init__(self, name):
self.name = name
def add_trick(self, trick):
self.tricks.append(trick)
>>> d = Dog(‘Fido’)
>>> e = Dog(‘Buddy’)
>>> d.add_trick(‘roll over’)
>>> e.add_trick(‘play dead’)
>>> d.tricks # unexpectedly shared by all dogs
[‘roll over’, ‘play dead’]
|
Call class in Python
Each class in Python can have different methods, which are the same functions as in the class. Methods can add other properties to the class or do a specific task. Consider the following written class.
1
2
3
4
5
6
7
8
9
10
11
|
class Person:
def __init__(self, person_name, person_age):
self.name = person_name
self.age = person_age
def Print_Person_Profile(self):
print ‘Name: ‘, self.name
print ‘Age: ‘, self.age
def Add_Phone(self, person_phonenumber):
self.phone = person_phonenumber
|
Call the whole module in Python programming
Calling a class is like calling a module. There are two ways to call a class:
1. Calling the whole class module in Python with the Import command: Note the following code:
1
2
3
4
5
6
7
8
9
|
import MyClass
P1 = MyClass.Person(‘Ali’, 26)
P1.Print_Person_Profile()
P1.Add_Phone(44556677)
print P1.phone
خروجی
Name: Ali
Age: 26
44556677
|
2. Call one or more specific classes of the class module using the two commands import and from
1
2
3
4
5
6
7
8
9
|
from MyClass import Person
P1 = Person(‘Ali’, 26)
P1.Print_Person_Profile()
P1.Add_Phone(44556677)
print P1.phone
خروجی
Name: Ali
Age: 26
44556677
|
It should be noted that as long as the class module name is called using the import command, the written description of the class and its methods can be extracted using the help command. You can also use the help command to show the description of the functions written in the document.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
import MyClass
help (MyClass)
output
Help on module MyClass:
NAME
MyClass – Created on
FILE
c:\...\myclass.py
DESCRIPTION
@author:
CLASSES
Person
class Person
| Methods defined here:
|
| Add_Phone(self, person_phonenumber)
|
| Print_Person_Profile(self)
|
| __init__(self, person_name, person_age)
|
We hope that this article has been of interest to you dear programmers and that you can use it well in projects when using the class in Python.