This lesson is devoted to explaining the basic concepts of “object-oriented programming” and is the last lesson in “basic” leveling in this book. The purpose of this lesson is to acquaint readers with the general concepts of object-oriented programming, not to teach it; More details on object-oriented programming, along with tutorials on how to implement its concepts in Python, will be explored in other lessons. This lesson also mentions the structure of objects and classes in the Python language, which will be a prerequisite for future lessons.
Object-Oriented Programming
” Object-Oriented Programming ” or OOP for short is a pattern or way of thinking in programming that is derived from the real world and has been around since the 1960s. The language that supports this pattern is called “object-oriented language”; Simula 67 and Smalltalk are the first object-oriented programming languages. The idea of object-oriented programming arose in response to some needs to which existing patterns did not meet; Needs such as: the ability to solve all complex problems (Complex), “Data Hiding” (Data Hiding), “Reusability” (Reusability) more, less dependence on functions, high flexibility and …
The object-oriented programming approach is “bottom-up”; That is, first small units of the program are created, and then by linking these units, larger units and finally a complete form of the program are created. Object-oriented programming is presented in the form of two concepts, ” Class ” and ” Object “. Each class is a unit of the program that holds a number of data and operations, and each object is a specific state of a class.
In object-oriented programming, each program is thought of as small entities that are actually objects and interact with each other. To have these objects, we must first define program classes; Each class defines the “Behavior” and ” Attributes ” of the objects to be created. We can create as many objects as we want from a class. Each object represents a ” state ” or an ” instance ” of its class.
For example, a factory can produce a car model in the form of a large class. Obviously, this factory includes smaller parts such as: electrical system, wheel system, fuel system, cooling system, engine, etc .; In this example, each of these sections is a class that must be created before the factory class, but they can also include other smaller classes instead. Since each class exists by its own objects; Examples of these classes should be created within the factory class. Placing objects in another class structure creates a larger entity. Now, with each instance of the factory class, a new object or entity is created that contains all the objects in those classes. The object of the factory class in this example is a car.
Each object in a class is called an instance of that class, and whenever an object in a class is created, an instance of it is actually created. This action is called ” instantiation ” in object-oriented programming. Accordingly, there are two types of classes in object-orientation: 1- Ordinary classes that have the ability to model and are called “Concrete Class” 2- Classes that do not have the ability to model and are called “Abstract Class” .
Another concept in object-oriented programming is “Encapsulation“. Capsulation means putting the elements of a structure in the form of a new entity. In object-oriented programming, by creating each instance of a class, its elements (attributes and behaviors) are placed in the form of a new entity called an “object”. Encapsulation in object-orientation is a possibility to hide data; In this situation, objects interact with each other without even the slightest awareness of each other and how they work.
We said that each class holds a number of data and operations within it, and we also said that each class defines the behavior and attributes of the objects from which it is to be created; We will now give a more complete definition: Each class consists of two parts, “Data Members” and “Member Functions”. Data members are actually the variables within the class that express the properties or attributes of an object and are referred to in object orientation as ” Field ” or ” Attribute “. Member functions are also operations or tasks that an object in the class can perform; Member functions can be thought of as expressing the behavior of class objects. In object-oriented programming, these functions are called ” methods “.
After prototyping, the object contains all the data members and member functions defined by the corresponding class, and to access them, the template: “object name + dot + attribute or method name ()” is used. Like:
car_object.color
car_object.drive()
As you will see when implementing the class; By creating each instance of the class, a specific method is executed automatically in it. This method is « constructive » (Constructor) and it is called ” initialize » (Initialization) object. This ensures that all data members are valued before using the object in the program.
For example, let’s go back to the car class and consider for those attributes: body color, tank capacity, maximum speed and methods: driving, receiving fuel, refueling, adjusting speed, stopping. We can now create our desired attributes, objects, or objects from this class by setting them. For example: two blue cars with a tank capacity of 20 liters and a maximum speed of 80 km / h or a pink car with a tank capacity of 40 liters and a maximum speed of 160 km / h, all three of which have all the methods of the class:
So far we are familiar with the concepts of “class”, “adjective”, “method”, “object”, “prototyping” and “encapsulation”; Went on to explain three concepts of object-oriented programming, including ” inheritance » (Inheritance), « polymorphism » (Polymorphism) and ” abstract ” or ” abstraction » (Abstraction), we will.
Inheritance:
Inheritance is a form of code “reusability” that enables the programmer to create new classes by inheriting the attributes and methods of one or more existing classes.
For example, suppose the owner of a car factory class in the previous example intends to produce a new car model with a freight approach; Therefore, it must prepare a new class to produce it. But the new class, in addition to the attributes (loading capacity, etc.) and methods (loading, unloading, etc.), has its own attributes (body color, tank capacity, etc.) and methods (driving, refueling, stopping, etc.). …) needs the same in the previous class; In this case, there is no need to redefine them and the attributes and methods of the previous class can be inherited in the new class.
The inherited class is called “Parent Class” or “Base Class” or “Superclass” and the inheriting class is called “Child Class” or “Derived Class” or “Subclass” . It becomes.
Inheritance is expressed by the IS-A Relationship; This ratio says that the child class is a type of what is a basic class. Class A inherits from Class B; In this case we say: A is a type of B, which means it is true to say: “apple” is a kind of “fruit” or “car” is a kind of “vehicle”, but note that this is a one-way connection of the child class It belongs to the basic class, and we cannot say: “fruit” is a kind of “apple” or “vehicle” is a kind of “car”.
Classes can be independent, but when they enter into inheritance relationships, they form a hierarchy structure in the form of a tree. Consider, for example, the structure of the lower inheritance hierarchy, which is related to some geometric shapes. Arrows indicate the is-a ratio.
In object-oriented programming than other titled “than it is-a » (HAS-A Relationship) that expresses a concept called ” combined » (Composition) is another form of reusability of code, but conceptually different from a hereditary base. This ratio is expressed when it is sampled within a class (such as: C) from another class (such as: D); That is, a C-class object must have a D-class object inside; In this case we say: C has a D. Remember we read that the car class is made up of smaller classes; For example, the engine class – that is, within this class an object of the engine class is created, we can now say: “car” has an “engine”.
Polymorphism:
The concept of polymorphism expresses the ability of the child class to define the methods that exist in the basic class. Consider, for example, the two classes of “fish” and “cat,” both of which inherit from a class called “animals.” In the animal class, there is a method called “eating” which is a common practice among all animals, but because it is done differently in fish and cats, both of these classes need to have their own “eating” method. This is where the method is redefined in the child classes, this is called the “Method Overriding”. By overriding a method, the base class method is overshadowed by the same method in the child class and is hidden from the child class objects.
Abstraction:
With the concept of polymorphism is object-oriented programming abstraction and by the concept of ” abstract classes » (Abstract Classes) and ” methods singles » (Abstract Methods) is presented.
“Single class” is a class that contains one or more “single methods” and “single method” is a method that has been declared but its body has not been defined. Single classes have no prototyping capability and cannot be created from objects; Because the purpose of their development is to be at the highest level (or several levels above) of the inheritance tree, as a base class for inheriting lower classes. The idea of designing a single classroom is to determine a development plan for its child classes; Determining the necessary attributes and methods, but leaving the definition of methods to the child classes. Consider, for example, the three classes of “fish,” “cat,” and “dove.” Apart from their specific behaviors (such as “flying” in pigeons or “swimming” in fish), these classes share a series of behaviors such as “breathing”, “eating” and so on. The proper way to develop these classes is to establish a “base class” for the common and inherited behaviors of all three. But since each one conducts these common behaviors differently; The correct way is to consider a “single class” as their “base class”; In this case, each of the classes, while knowing the necessary behaviors, can define them according to their wishes.
Objects in Python
In addition to being an object-oriented programming language, Python is structured on an object-oriented basis, stating that everything in Python is an object . Objects are Python abstracts to represent “Data Types”. In other words, all data in a Python program is either directly an object or is created from relationships between objects. For example 56
, functions and even classes offered by an object."!Hello World"
Each object in Python contains an ” identity “, a ” type ” and a ” value “.
-
The “identifier” is assigned to the object at the time of creation and is immutable. The function
()id
returns the object ID as an integer, which in CPython represents the address of the object in memory:>>> id(5) 140468674877440 >>> num = 0.25 >>> id(num) 140468676592120 >>> msg = "Hello World!" >>> id(msg) 140468675425264
Each object in Python has a “type” that defines supported operations as well as possible values for the object. The type of each object is ()type
visible by the function and is as immutable as the identifier:
>>> # python 3.x
>>> type(127)
<class 'int'>
>>> # python 2.x
>>> type(127)
<type 'int'>
consideration
All integers in Python are an object of type
int
. [You will be introduced to the built-in types of objects in Python by future lessons.]
-
The “amount” of some objects in Python is called “mutable” ; this group of objects is called “mutable” ; But the value of others cannot be changed (such as numbers: objects
127
), which are called “immutable” objects .
Classes in Python
From version 2.2, the design of classes in Python changed [ New-style Classes ], although the old structure remains in version 2x. [The basis of training in this book is the new design.]
In the new structure, the concept of “type” is designed equal to the concept of “class”. In this structure, each class itself is an object of a class called “type” and also all classes inherit from a class called “object”:
>>> # Python 3.x
>>> num = 3
>>> num.__class__
<class 'int'>
>>> type(num)
<class 'int'>
>>> type(type(num))
<class 'type'>
>>> type(num).__class__
<class 'type'>
>>> type(num).__bases__
(<class 'object'>,)
consideration
Displays the
__class__
class name attribute of an object and the__bases__
class name attribute of a class.
The definition of class
In Python, a keyword class
is used to define a class ; Like the template below:
class ClassName:
<statement-1>
.
.
.
<statement-N>
The keyword defining a class – class
– is an executable statement. A class has no effect on the program before executing its command. This condition allows even a class to be if
defined in the body of the condition statement ( ) or inside the body of a function. [Behind the Scenes]: By executing the class definition command, an object of type type is created in memory and the class name is used to refer to that object.
After the keyword, class
the class name (at the user’s request) is written. The first line of the definition, like all compound commands that are usually written in a few lines and have a heading, ends in a character :
. From the second line, with a uniform indentation, the commands of the class body are written:
>>> # Python 3.x
>>> class MyClassName:
... pass
...
>>>
>>> type(MyClassName)
<class 'type'>
>>> MyClassName.__bases__
(<class 'object'>,)
>>>
consideration
In cases where we still do not want to write commands related to the body of a command such as a class; We can use the command
pass
. Nothing will be done by executing this command.
>>> # Python 2.x
>>> class MyClassName(object):
... pass
...
>>>
>>> type(MyClassName)
<type 'type'>
>>> MyClassName.__bases__
(<type 'object'>,)
>>>
All classes in Python 3x are implicitly inherited from the object class and do not need to be inserted by the programmer; But in version 2x, if we want to follow the new design of the classes, we must explicitly inherit from this class.
In the inheritance discussion, the name of the base class (s) is written in parentheses in front of the class name. If inherited from several classes, their names must be separated by a comma:
>>> # Python 3.x
>>> class ChildClassName(BaseClassNameOne, BaseClassNameTwo):
... pass
...
>>>
>>> ChildClassName.__bases__
(<class '__main__.BaseClassNameOne'>, <class '__main__.BaseClassNameTwo'>)
consideration
As we know,
__main__
refers to the name of the module.
Carefully in the example code above, you will notice that the object class is no longer among the base classes. The reason for this is that the ChildClassName class is now in an inheritance hierarchy, and its base classes inherit from this class.
>>> # Python 2.x
>>> class BaseClassNameOne(object):
... pass
...
>>>
>>> class BaseClassNameTwo(object):
... pass
...
>>>
>>> class ChildClassName(BaseClassNameOne, BaseClassNameTwo):
... pass
...
>>>
>>> ChildClassName.__bases__
(<class '__main__.BaseClassNameOne'>, <class '__main__.BaseClassNameTwo'>)
To get the name of all the base classes in the inheritance hierarchy of a particular class, we can use the function ()getmro
inside the module inspect
[ Python documents ]; As below:
>>> # Python 3.x
>>> import inspect
>>> inspect.getmro(ChildClassName)
(<class '__main__.ChildClassName'>, <class '__main__.BaseClassNameOne'>, <class '__main__.BaseClassNameTwo'>, <class 'object'>)
>>> # Python 2.x
>>> import inspect
>>> inspect.getmro(ChildClassName)
(<class '__main__.ChildClassName'>, <class '__main__.BaseClassNameOne'>, <class '__main__.BaseClassNameTwo'>, <type 'object'>)
consideration
The output of the function is
()getmro
sorted; In this way, in a hierarchy, the desired class starts and ends with the object class. Basic level classes are also arranged in the order in which they are written in the child class.