How to understand Python's object orientation in the simplest and most popular way?

Object-Oriented Programming (OOP), whenever we see this term, we associate it with Java. In fact, Java has popularized the object-oriented programming style. In addition to Java, there are many OOP languages, such as C++, C#, Swift, JavaScript, php, etc., and of course, Python.

Python provides an object-oriented programming style. Today, I will explain Python object-oriented step by step to ensure that even novices with zero foundation can thoroughly understand Python object-oriented after reading this article. In this article, I will introduce you to the basic knowledge of Python object-oriented programming from the following topics:

1 Class
2 Object
3 Inheritance
4 Attribute
5 Method

1 Basic concepts

1.1 Class

What are classes in OOP?

First, understand the concept with the help of a picture.

From the picture above, we can see the following information: classes, objects, properties, methods and a Pikachu.

What does this have to do with OOP? Well, the above image is exactly what helps us understand the concept of OOP.

So, now onto the first topic. What does class mean in OOP? The definition of a class is "A class is a collection of objects of the same type." Relate this definition to the example above. In this picture, we can see that there is a rectangular box called Pokemon, which is the name of the class.

So, in short, a class is nothing but a collection of objects. Therefore, all pokemon in the pokemon universe are under the "pokemon" category.

To ensure understanding, let’s give another example. Take the cars we often see as examples, such as Nissan, Tesla, Ford, and Toyota. These can be understood as individual objects, and "cars" are the synthesis and collection of this series of objects.

1.2 Objects

The concept of objects has been mentioned repeatedly before, and I will explain it in detail next. In OOP, an object is a component or member of a class. Considering our elf example, each elf is an object of the elf class. For example. Pikachu is an object of the Pokemon class. For example, Toyota is an object of automobiles.

1.3 Properties

Going back to our Pokemon example, let's focus on Pikachu in the image. Watch it for a while. What do you see?

By observing the image of Pikachu, we can see that it has two ears, two hands, two legs, two small red dots on its cheeks, and a prominent yellow color. In the adjacency table in the picture we also see a few things like name="Pikachu", type="electric" and health=70.

Therefore, all these are called attributes, which are elements that provide additional information about a class or object. In this case, all these properties provide additional information about the Pikachu object, such as color, health, etc.

1.4 Method

In the Pokemon example, you can see things like attack(), dodge(), evolve() in the diagram, these are called methods. Explained more simply, a method base is an action associated with a specific object. In this case, the actions are related to our Pikachu object. At this point, many students must have a basic understanding of some concepts in object-oriented. Next, let’s put it into practice and see how to use Python object-oriented.

2 Practice

2.1 Create classes

class Pokemon():

As you can see from the code above, when creating a class in Python, you need to follow a certain structure.

Starting with the keyword class, this way Python can recognize that what we are creating will be treated as a class. The keyword class is followed by the name of the class, in this case Pokemon.

Finally, it is followed by () and then the : character. Of course, the class has not been created yet, and some other content is needed.

Create __init__ method

Continuing with our class creation task, the next step involves creating a very special method called __init__.

You may ask: What is this __init__ method?

To simply understand this concept, the init method can be thought of as similar to the constructor method in Java.

First give the specific code:

class Pokemon():
  def __init__():

As you can see from the above code, the __init__ method has been created in Python. Here, we noticed one thing, that is, the keyword named def, which is mainly used to create functions or methods in Python.

Add properties

The __init__() method is currently defined, however, it is still not fully defined.

Some parameters still need to be passed in the __init__() method to complete its definition.

Next, let's add these parameters to the __init__() method.

class Pokemon():
  def __init__(self,name,Type,health):
    self.name = name
    self.Type = Type
    self.health = health

As you can see from the above code, I passed a lot of parameters in the __init__() method.

Now let's go back and understand what parameters are passed here. Remember the concept introduced earlier, right?

We talked about Pikachu being yellow, having two red dots on his cheeks, and so on. These are the properties associated with an object, and in this __init__() method, we define these properties.

In addition, let me explain another question: What is the use of self? To explain simply, self is a keyword responsible for connecting these properties to our class, which is Pokemon in this case.

2.2 Creation method

So far, we have declared our class, a special method named __init__() and the attributes of the class.

Next, move on to the final part, the creation of the method.

class Pokemon():
  def __init__(self,name,Type,health):
    self.name = name
    self.Type = Type 
    self.health = health
  def attack(self):
    print("Electric attack!")
  def dodge(self):
    print("Pikachu Dodge!")
  def evolve(self):
    print("Evolving to Raichu!")

As you can see from the code above, I create 3 methods named attack(), dodge(), evolve().

Looking at this code, you can see that we pass a parameter named self to each method.

Here, the self keyword is being used to connect this method with our class.

So far, a complete class has been created.

2.3 Create objects

First, give the code for creating an object. Here I create an object named pk1:

pk1 = Pokemon("Pikachu","Electric",120)

After creating the object, we can do many operations.

Access properties

We can access the properties of the object through the <object name>.<property> method. Let’s take a look at the specific code:

pk1.name  # 输出:Pikachu
pk1.Type  # 输出:Electric
pk1.health  # 输出:120

Access method

Access methods and access property types <object name>.<method>, similarly, use specific code to explain it more clearly:

pk1.attack() # 输出:Electric attack!
pk1.dodge() # 输出:Pikachu Dodge!
pk1.evolve() # 输出:Evolving to Raichu!

At this point, we have explained the basic content of Python object-oriented programming. Next, let’s take it a step further and introduce inheritance in object-oriented programming.

2.4 Inheritance

Inheritance is one of the key concepts in OOP and again, it will be easier to understand this concept with the help of a simple example.

Consider the example of a supercar, the McLaren 720S spyder, which is a supercar. As you can see, like most other cars, it has some common features such as doors, windshield, 4 wheels, headlights, taillights, etc. However, since it is a supercar, it has its own custom features, such as a 720-horsepower V8 turbocharged engine, a custom transmission developed by McLaren, and a custom AWD (all-wheel drive) system.

Now to relate this to object-oriented terms, we can say that the car inherits certain characteristics from its parent class, which in this case is a car class in the first place. This is the concept behind "inheritance". Inheritance is a phenomenon whereby an element acquires characteristics from its parent class.

In this case, the McLaren 720S spyder inherits all the common characteristics of the automotive class, but at the same time, it has certain special characteristics of its own. Superclasses and Subclasses The class that our elements inherit from (the car class in this case) is called the superclass and is universal. The class that inherits these characteristics is called a subclass (Subclass), which is special in nature.

Next, implement these concepts in Python. In this example, I will create two classes – one is called Car, which is the super class. The other is a class called McLaren, which is a subclass. This McLaren class will inherit all properties of the Car class.

class Car():
  def __init__(self,ndoors,nwheels,tailLight,headLight):
    self.ndoors = ndoors
    self.nwheels = nwheels
    self.tailLight = tailLight
    self.headLight = headLight

Here, the first class named Car has been created. Now, we will create a new class called McLaren which will inherit all the properties of this class.

class McLaren(Car):
  def __init__(self,ndoors,nWheels,tailLight,headLight,Engine,Wheel_Drive):
    Car.__init__(self,ndoors,nWheels,tailLight,headLight)
    self.Engine = Engine
    self.Wheel_Drive = Wheel_Drive
  def Drive(self):
    print("I am driving McLaren 720S Spyder")

As you can see in the above code, since the McLaren class inherits the Car class, we use Car as one of the parameters when creating the McLaren class. This is a mechanism of Python class inheritance.

Next, we create a McLaren object and verify whether it inherits the Car feature.

mk1 = McLaren("4","4","Yes","Yes","V8","AWD")

Then, access the object's properties again:

mk1.Engine # 输出:V8
mk1.Wheel_Drive # 输出:AWD

Here we can see that we can access special properties specifically defined in the McLaren object that are not available in the base class Car. Here we have inherited our base class, let's see if those properties in the base class are inherited in our McLaren class.

mk1.headLight # 输出:YES
mk1.ndoors # 输出:4
mk1.nWheels # 输出:4

As you can see, the newly created object of the McLaren class inherits all the characteristics of the Car base class, indicating that inheritance is correctly implemented in this context.

So far, from basic concepts to practice, it covers concepts and specific implementations of classes, objects, special methods, attributes, methods, etc. in Python. It has comprehensively introduced the relevant knowledge and content of Python's objects. Do you have a thorough understanding of Python? Face to face?

Technical reserves about Python

Here I would like to share with you some free courses for everyone to learn. Below are screenshots of the courses. Scan the QR code at the bottom to get them all.

1. Python learning routes in all directions

Insert image description here

2. Learning software

If a worker wants to do his job well, he must first sharpen his tools. The commonly used development software for learning Python is here, saving everyone a lot of time.
Insert image description here

3. Study materials

Insert image description here

4. Practical information

Practice is the only criterion for testing truth. The compressed packages here can help you improve your personal abilities in your spare time.
Insert image description here

5. Video courses

Insert image description here

Well, today’s sharing ends here. Happy time is always short. Friends who want to learn more courses, don’t worry, there are more surprises~Insert image description here

Guess you like

Origin blog.csdn.net/Everly_/article/details/133344551