The purpose of this article is to make it as easy as possible for people (including myself) who are allergic to object-oriented programming, "I'm not afraid of object-oriented programming."
Since I am a beginner in programming, please understand that the explanation of terms may be different or some expressions may be difficult to understand.
[Object Oriented Programming-Wikipedia](https://ja.wikipedia.org/wiki/%E3%82%AA%E3%83%96%E3%82%B8%E3%82%A7%E3%82%AF % E3% 83% 88% E6% 8C% 87% E5% 90% 91% E3% 83% 97% E3% 83% AD% E3% 82% B0% E3% 83% A9% E3% 83% 9F% E3 % 83% B3% E3% 82% B0)
What is object-oriented programming?
Object-oriented programming (object-oriented programming, English: object-oriented programming, abbreviation: OOP) is to combine data and methods that are closely related to each other into an object, which has different properties and roles. It is a software development method that builds the entire program through various definitions of objects and the settings of various processes that interact with these objects.
What is object-oriented?
The term object-oriented itself was coined by computer scientist Alan Kay. Kay, who was impressed by the design of the language "Simula" released in 1962, said this coined word for the first time in explaining the language design of "Smalltalk", which he started publishing in 1972. It was sent to the world. It should be noted that the object-oriented programming centered on message passing, which Kay showed, is not widely recognized, and only focuses on the program concept of objects. At the same time, object-oriented programming away from Kay's hands shifted to an interpretation centered on abstract data types, and with the opportunity of "C ++" released by computer scientist Bjarne Stroustrup in 1983, Japan The paradigms of encapsulation, inheritance, and polymorphism, which are generally called the three major elements of OOP, have been established.
A collection of data and methods that are closely related to each other.
--The source code is written in Python 3.9. ――I am writing the source code using a car as an example.
It corresponds to the blueprint when making a car.
Below is the sample code.
sample.py
class Car:
def __init__(self):
pass
It corresponds to the car itself (entity) that was made.
Below is the sample code.
sample.py
class Car:
def __init__(self):
pass
car = Car() #instance
For example, vehicle type, number, color, engine, tires, etc ... And there are also accelerators and brakes.
Let's add (some of) this information to the blueprint.
Below is the sample code.
sample.py
class Car:
def __init__(self, name, color):
self.name = name #Car name
self.color = color #Car color
def start_engine(self):
print("I started the engine.")
def stop_engine(self):
print("I turned off the engine.")
def accelerator(self):
print("I stepped on the accelerator.")
def brake(self):
print("I stepped on the brake.")
mycar = Car("Prius", "White") #Instance generation
mycar.start_engine() #I started the engine. Is displayed
mycar.accelerator() #I stepped on the accelerator. Is displayed
mycar.brake() #I stepped on the brake. Is displayed
mycar.stop_engine() #I turned off the engine. Is displayed
Let's leave this for the time being.
Earlier, I mentioned a little in the Wikipedia quote.
Encapsulation in programming (encapsulation or English: encapsulation) means to combine data (attributes) and methods (procedures) into one object and hide its contents. The concept of encapsulation can be seen as one of the constructs of information hiding in D.L. Parnas.
Objects in object-oriented programming are created by encapsulating information by classes.
Encapsulation hides information that you do not want to disclose to the outside.
In Python, encapsulation is done by prefixing the variable name (or function name) with an underscore. However, in Python it is best not to encapsulate as much as possible. If there is one underscore, it should be used only within that class, In the case of two underscores (called dander), the use is more restricted. It's a bit special to call, but it doesn't mean you can't.
It may also be used to easily disguise complex processing. In that case, you should actively use it. If you compare it with a car, various children are done inside to start the engine, It's like the driver doesn't have to know it.
Below is the sample code.
sample.py
class Car:
def __init__(self, name, color):
self.name = name #Car name
self.color = color #Car color
self._age = "2020 model year" #Model year
self.__engine = "gasoline engine" #Engine type
mycar = Car("Prius", "White")
print(mycar._age) #Executable,Displayed as "2020 model year"
mycar._age = "2019 model year" #Substitution is also possible * Should not be
print(mycar.__engine) #This will cause an error
# AttributeError: 'Car' object has no attribute '__engine'
print(mycar._Car__engine) #Executable,It says "gasoline engine" but shouldn't
[Inheritance (programming)-Wikipedia](https://ja.wikipedia.org/wiki/%E7%B6%99%E6%89%BF_(%E3%83%97%E3%83%AD%E3%82) % B0% E3% 83% A9% E3% 83% 9F% E3% 83% B3% E3% 82% B0))
Inheritance (inheritance) is one of the concepts that make up object orientation. When one object inherits the characteristics of another object, it is said that there is an "inheritance relationship" between the two. (Omitted) In general, when B inherits A, the semantic relationship (Is-a relationship) of "B is a A." (B is a type of A) holds. Therefore, it is often not appropriate to have an inheritance relationship between semantically unrelated classes just because they have the same behavior.
There is "delegation" in a concept similar to inheritance, but in inheritance, the inheritance relationship once determined is usually not changed, but the subject of delegation can be changed as needed.
There are aggregation and composition as concepts that are different in hierarchy from inheritance with Is-a relationship, but this is an inclusion relationship in which the relationship between classes is Has-a, and it is between classes. Relationships are sparser than inheritance.
In summary, it is better to use inheritance if the is-a relationship holds. However, it is better to refrain from using inheritance unnecessarily.
If you compare it with a car Sports car is a car Special vehicle is a A car, etc.
Below is the sample code.
The Car class is the same as before.
sample.py
class Car:
def __init__(self, name, color):
...
...
class SportCar(Car):
def __init__(self, name, color):
super().__init__(name, color)
class SpecialCar(Car):
def __init__(self, name, color):
super().__init__(name, color)
The inherited class is called the parent class, and the inherited class is called the child class.
In the sample code above, the Car class is the parent class and the SportCar and SpecialCar are the child classes.
The child class super () .__ init__ (name, color)
calls the parent class __init__
.
[Polymorphism-Wikipedia](https://ja.wikipedia.org/wiki/%E3%83%9D%E3%83%AA%E3%83%A2%E3%83%BC%E3%83%95%E3 % 82% A3% E3% 82% BA% E3% 83% A0)
Polymorphism describes the nature of the type system of a programming language, and that each element of the programming language (constants, variables, expressions, objects, functions, methods, etc.) belongs to multiple types. Refers to the property of forgiving.
If you look at Wikipedia, you probably don't understand what you're saying, so take a look at the sample code.
Below is the sample code.
sample.py
class Car:
def __init__(self, name, color):
...
def accelerator(self):
print(f"I stepped on the accelerator.({self.name})")
def brake(self):
print(f"I stepped on the brake.({self.name})")
class SportCar(Car):
...
class SpecialCar(Car):
...
cars = [Car("Prius", "White"), SportCar("Ferrari", "Red"), SpecialCar("ambulance", "White")]
for car in cars:
car.accelerator()
car.brake()
Execution result.
I stepped on the accelerator.(Prius)
I stepped on the brake.(Prius)
I stepped on the accelerator.(Ferrari)
I stepped on the brake.(Ferrari)
I stepped on the accelerator.(ambulance)
I stepped on the brake.(ambulance)
By preparing a method with the same name, it is possible to use it without being aware of the type (class).
That's all for the explanation.
From now on, I will modify the source code to a program that seems to be object-oriented programming.
Click here for the original source code
sample.py
class Car:
def __init__(self, name, color):
self.name = name #Car name
self.color = color #Car color
def start_engine(self):
print("I started the engine.")
def stop_engine(self):
print("I turned off the engine.")
def accelerator(self):
print("I stepped on the accelerator.")
def brake(self):
print("I stepped on the brake.")
class SportCar(Car):
def __init__(self, name, color):
super().__init__(name, color)
class SpecialCar(Car):
def __init__(self, name, color):
super().__init__(name, color)
cars = [Car("Prius", "White"), SportCar("Ferrari", "Red"), SpecialCar("ambulance", "White")]
for car in cars:
car.accelerator()
car.brake()
I'll fix it a little.
The car does not have the functions of start engine and stop engine.
There is only one engine button.
So ...
Combine start_engin (self)
and stop_engine (self)
into one.
Also, make sure that the engine is running and the engine is running.
sample.py
class Car:
def __init__(self, name, color):
self.name = name #Car name
self.color = color #Car color
self._engine = False #True when the engine is running,False when not on
def engine(self):
print(f"[{self.name}]", end=" ")
self._engine = not(self._engine)
if self._engine:
print("I started the engine.")
else:
print("I turned off the engine.")
def accelerator(self):
print(f"[{self.name}]", end=" ")
print("I stepped on the accelerator.")
def brake(self):
print(f"[{self.name}]", end=" ")
print("I stepped on the brake.")
class SportCar(Car):
def __init__(self, name, color):
super().__init__(name, color)
class SpecialCar(Car):
def __init__(self, name, color):
super().__init__(name, color)
cars = [Car("Prius", "White"), SportCar("Ferrari", "Red"), SpecialCar("ambulance", "White")]
for car in cars:
car.engine()
car.accelerator()
car.brake()
car.engine()
Execution result.
[Prius]I started the engine.
[Prius]I stepped on the accelerator.
[Prius]I stepped on the brake.
[Prius]I turned off the engine.
[Ferrari]I started the engine.
[Ferrari]I stepped on the accelerator.
[Ferrari]I stepped on the brake.
[Ferrari]I turned off the engine.
[ambulance]I started the engine.
[ambulance]I stepped on the accelerator.
[ambulance]I stepped on the brake.
[ambulance]I turned off the engine.
Is it like this?
I couldn't think of a good example, so it may have been difficult to understand. I think that object-oriented programming will be more useful as the number of people increases.
This time it ends.
Until the end Thank you for reading. If you have any mistakes or advice, I would appreciate it if you could comment.
Recommended Posts