Home > Backend Development > Python Tutorial > Introduction to object-oriented programming in Python language (with code)

Introduction to object-oriented programming in Python language (with code)

不言
Release: 2019-03-09 13:56:35
forward
2899 people have browsed it

This article brings you an introduction to object-oriented programming in Python language (with code), which has certain reference value. , friends in need can refer to it, I hope it will be helpful to you.

Object-oriented Python language

Object-oriented programming, or OOP, is often mentioned for object-oriented languages. To concepts such as encapsulation, inheritance, and classes.
The origin of object-oriented: Based on the philosophy that everything is an object, the core idea is to objectify and modularize our programs. In the Python language, class is commonly used to name a class, such as class Person(), class Student, etc. There are often attributes and behaviors in classes. For example, the Person class has attributes such as name, height, weight, etc. These Python behaviors include eating, sleeping, making friends, etc. Through classes, we can easily implement later calls without having to write some repeated codes again, which greatly improves the efficiency of programming. Therefore, object-oriented programming languages ​​are currently widely used.
Object-oriented has three major characteristics: inheritance, encapsulation, and polymorphism

1 Inheritance
Inheritance concept: If a class inherits another class, the inherited class is called a subclass, and the inherited class is the parent. kind.
Purpose: To enable code reuse.
Understanding: The relationship between the subclass and the parent class is not the parent-child relationship in daily life. The relationship between the subclass and the parent class is a specialization and generalization. It is an is-a relationship, and the subclass is the parent class. More detailed classification. For example, if class dog inherits from animal, it can be understood as dog is an animal. Pay attention when designing inheritance.
Result: After inheritance, the subclass automatically has the attributes and methods of the parent class, and the subclass can write its own unique attributes and methods. The purpose of methods is to extend functions. Subclasses can also override the methods of the parent class, which is the rewriting of methods.

2 Encapsulation
Concept: Encapsulation, also known as information hiding, refers to the use of abstract data types to encapsulate data and data-based operations so that they form an indivisible independent entity, and the data is protected Within the abstract data type, the internal details are hidden as much as possible, and only some external interfaces are retained to connect them with the outside. The rest of the system can communicate and interact with this abstract data type only through authorized operations wrapped around the data. That is to say, the user does not need to know the implementation details of the internal methods of the object, but can access the object according to the external interface (object name and parameters) provided by the object.
Benefits: (1) Clear division of labor. After encapsulating the code that can implement a specific function into an independent entity, each programmer can call it when needed, thus realizing professional division of labor. (2) Information concealment and implementation details. By controlling access rights, you can hide information that you don't want client programmers to see. For example, if a customer's bank password needs to be kept secret, you can only develop permissions for that customer.
3 Polymorphism
Concept: The same thing, when the same method is called and the parameters are the same, the behavior is different.
Understanding: Subclasses appear as parent classes, but they still implement their own methods when doing things. When a subclass appears as a parent class, it requires upward transformation (upcast). Upcasting is automatically implemented by the JVM and is safe, but downward transformation (downcast) is unsafe and requires forced conversion. When a subclass appears as a parent class, its own unique properties and methods will not be available.
The difference between "process-oriented" and "object-oriented"
Process-oriented is to analyze the steps required to solve the problem, and then use functions to implement these steps step by step. When using them, just call them one by one; Object-oriented is to decompose the transaction that constitutes the problem into individual objects. The purpose of establishing the object is not to complete a step, but to describe the behavior of something in the entire step of solving the problem.
You can use examples in life to understand process-oriented and object-oriented. For example, after completing a game, the process-oriented design idea is to first analyze the steps of the problem:
1. The game starts, 2. Start competing, 3. Midway Transcend, 4. Decide the winner. Implement each of the above steps in a different way.
If it is an object-oriented design idea to solve the problem. Object-oriented design solves problems from another perspective. The entire competition can be divided into 1. Competition objects 2. Competition rules 3. Result evaluation, etc.
The following is a small example to illustrate the object-oriented programming process of Python language:

一、
#1 定义一个类,其中类名是学生
#2 学生具有的属性
#3 学生具有哪些行为
#4 具体化两个学生,实例化类型
class Student(object):
    name = " "
    age = 12
    weight = 50
    school = "wuhan university"
    def eat(self,orange):
        print("l love orange")
    def study(self):
        print("let me study!")
stu1 = Student()
stu2 = Student()
print(stu1)
print(stu2)
print(stu1.name)
print(stu1.age)
print(stu2.name)
print(stu2.age)

二、
#进一步优化:通过上面的程序我们发现他们最终输出的对象的属性一样,但是事实上他们是两个不同的学生,他们的名字,年龄并不相同,那么接下来需要做的就是给他们各自赋予各自的属性,利用类名.属性=某个值,和方法的调用一样也是类名.方法名
class Student(object):
    name = " "
    age = 12
    weight = 50
    school = "wuhan university"
    def eat(self,orange):
        print("l love orange")
    def study(self):
        print("let me study!")
stu1 = Student()
stu1.name="王"
stu1.age = 20

stu2 = Student()
stu2.name = "张"
stu2.age = 50
print(stu1)
print(stu1.name)
print(stu1.age)
print(stu2)
print(stu2.name)
三、
#进一步优化:通过第二个程序我们发现在定义对象的属性时我们还需要将所得属性命名在写一次,这样显然比价麻烦,于是有了更好的属性命名方法,我们可以使用初始化 
def __init__(self,、、、),最后在命名属性的时候只需要在类名后面的括号中填写具体的属性值即可,大大较少了代码量。

class Student(object):
    def __init__(self,name,age,school):
        self.name = name
        self.age = age
        self.school = school
    def eat(self,orange):
        print("l love orange")
    def study(self):
        print("let me study!")
stu1 = Student("li",25,"scu")
stu2 = Student("sun",20,"wpu")
print(stu1)
print(stu2)
print(stu1.name)
print(stu1.school)
print(stu2.name)
print(stu2.school)
Copy after login

self represents the instance in the class, not the class. That instance calls the method in the class, then this self belongs to that Object, for example, add a method to Student to introduce itself.

class Student(object):
    def __init__(self,name,age,school):
        self.name = name
        self.age = age
        self.school = school
    def eat(self,orange):
        print("l love orange")
    def study(self):
        print("let me study!")
    def intro(self):
        print("my name is{},{} years old".format(self.name,self.age))
stu1 = Student("li",25,"scu")
stu2 = Student("sun",20,"wpu")
print(stu1)
print(stu2)
print(stu1.name)
print(stu1.school)
print(stu2.name)
print(stu2.school)
intro1 = stu1.intro()
intro2 = stu2.intro()
Copy after login

If you want to print out the attributes and other information of the object for the client to see, but because there are too many attributes, it is troublesome to print them out one by one. You can use __str__(), as follows:

class Student(object):
    def __init__(self,name,age,school):
        self.name = name
        self.age = age
        self.school = school
    def eat(self,orange):
        print("l love orange")
    def study(self):
        print("let me study!")
    def intro(self):
        print("my name is{},{} years old".format(self.name,self.age))
    def __str__(self):
        return "%s-%d"%(self.name,self.age)
stu1 = Student("li",25,"scu")
stu2 = Student("sun",20,"wpu")


print(stu1)
Copy after login

如果要是的Python中类的属性值不改变,那么在属性前加两个-,称为私有属性,private
如:
self.__money = money,不能再外面直接访问
print(stu1.__money)报错
但是在内部可以直接使用,如在方法eat中调用
如果属性名前是一个下划线,则他虽然可以在外部访问,但是约定俗成提示不要访问!!!

The above is the detailed content of Introduction to object-oriented programming in Python language (with code). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template