Python (four) object-oriented

1. Object

1. What is an object ?

An object is an area of ​​memory dedicated to storing data. Objects can store various data (such as numbers, booleans, codes, etc.).

  • The object consists of three parts:

    ①The identification of the object (id)
    ②The type of the object (type)
    ③The value of the object (value)

2. Programming ideas

Python is an object-oriented programming language.

  • Process-oriented : Process-oriented refers to decomposing the logic of our program into step by step, what to do first
  • Object -oriented : Object-oriented refers to assigning our programs to objects to operate, what do you do?

insert image description here

Second, the class (class)

(1) Definition of a class

1. What is a class ?

Defining a class is to define a template for this class of objects and define its properties and methods. Classes are also objects.

2. Class attributes and methods

  • Variables will become properties of the class instance, and all instances of the class can access properties in the form of object.property name
  • The function will become the method of the class instance , and all the class instances can call the method in the form of object.methodname ()

(2) Create a class

1, the basic structure of the class


class 类名([父类]) :#class关键字来声明一个类

    公共的属性...

    # 对象的初始化方法,类的构造方法
    def __init__(self,...):
        ...

    # 其他的方法    
    def method_1(self,...):
        ...

    def method_2(self,...):
        ...

2. Class constructor (magic method) _ init _

3. self in the method of the class

  • Every time the method is called, the parser will automatically pass the first argument, the first parameter is the calling classthe instance object itself, so at least one formal parameter must be defined in the method . Generally, we will name this parameter as self.

  • Self only exists in class methods, independent functions do not have to carry self. self is required when defining a method of a class, although it is not necessary to pass in the corresponding parameters when calling it.

  • You can bind various properties of an object to self. self.val = val, which means to assign the value of the external parameter val to the instance attribute val of the current instance object of the Myclass class.

  • self is not a keyword in python, and it can be named by other names, but for the sake of specification and easy understanding of readers, it is recommended to use self.

  • If you do not add self, it means that it is an attribute of the class (it can be referenced by "class name.variable name"), and adding self means that it is an attribute of an instance of the class (can be referenced by "instance name.variable name" ).

class Person:
    def say_hello(a):#方法每次被调用时,解析器都会自动传递第一个实参
        print('a参数:'.rjust(9,' '),a)#第一个参数,就是调用方法的对象本身,也就是类的实例本身

p1 = Person()#创建实例p1
print('实例对象p1:',p1)
p1.say_hello()

print('*'*100)
p2 = Person()#创建实例p2
print('实例对象p2:',p2)
p2.say_hello()

insert image description here

class Human():
    val = '哈哈哈'#类的属性,公共的属性
    def __init__(self,val = '我是人类'):#类的初始化方法,注意:构造方法的返回值必须是"None"
        self.val = val #通过self向类实例中初始化属性

    def yellow_people(self,val = '我是黄种人'):#类的方法(函数)
        self.val = val 
        self.val1 = '我自豪'
        return self.val,self.val1#多个返回值

    def white_people(self,val = '我是白种人'):
        self.val = val 
        return self.val

print(Human.val)#Human是一个类,通过Human.val(类名.变量名)可以引用类的属性,输出:哈哈哈
print(Human().val)#Human()创建了一个类的实例,val变量加了self,表示类的实例Human()的一个属性,通过Human().val(实例名.变量名)引用,输出:我是人类
print(Human().yellow_people())

insert image description here
Understanding of self in python

3. Encapsulation, Inheritance, Polymorphism

The three major characteristics of object-oriented:
Encapsulation: to ensure the data security
in the object Inheritance: to ensure the extensibility of the object
Polymorphism: to ensure the flexibility of the program

(1) Encapsulation

Encapsulation, as the name implies, is to encapsulate the content somewhere, and then call the content encapsulated somewhere.
For object-oriented encapsulation, it is actually to use the constructor to encapsulate the content into the object, and then obtain the encapsulated content directly or indirectly through the object.

(2) Inheritance

A new class is formulated on the basis of a class. This class can not only inherit the properties and methods of the original class, but also add new properties and methods. The original class is called the parent class, and the new class is called the child class.

# 定义一个类 Animal(动物),这个类中需要三个方法:run() sleep() bark()
class Animal:
    def run(self):
        print('动物会跑~~~')

    def sleep(self):
        print('动物睡觉~~~')

    def bark(self):
        print('动物嚎叫~~~')

# 有一个类,能够实现我们需要的大部分功能,但是不能实现全部功能
# 如何能让这个类来实现全部的功能呢?
#   ① 直接修改这个类,在这个类中添加我们需要的功能
#       - 修改起来会比较麻烦,并且会违反OCP原则
#   ② 直接创建一个新的类
#       - 创建一个新的类比较麻烦,并且需要大量的进行复制粘贴,会出现大量的重复性代码
#   ③ 直接从Animal类中来继承它的属性和方法
#       - 继承是面向对象三大特性之一
#       - 通过继承我们可以使一个类获取到其他类中的属性和方法
#       - 在定义类时,可以在类名后的括号中指定当前类的父类(超类、基类、super)
#           子类(衍生类)可以直接继承父类中的所有的属性和方法
#
#  通过继承可以直接让子类获取到父类的方法或属性,避免编写重复性的代码,并且也符合OCP原则
#   所以我们经常需要通过继承来对一个类进行扩展
class Dog(Animal):
    def bark(self):
        print('汪汪汪~~~')

    def run(self):
        print('狗跑~~~~')

class Hashiqi(Dog):
    def fan_sha(self):
        print('我是一只傻傻的哈士奇')

d = Dog()
h = Hashiqi()

d.run()#多态
d.sleep()#继承
d.bark()#多态
h.fan_sha()

insert image description here

(3) Polymorphism

When the subclass and the superclass have the same method, the subclass's method will override the superclass's method, and such code will always call the subclass's method at runtime, which is polymorphism.

Four, various object-oriented methods

(1) Static method ( @staticmethod )

(2) Class method (@classmethod)

(3) Property method (@property)

class Person:
    def __init__(self,name,age):
        self._name = name
        self._age = age

    # property装饰器,用来将一个get方法,转换为对象的属性
    # 添加为property装饰器以后,我们就可以像调用属性一样使用get方法
    # 使用property装饰的方法,必须和属性名是一样的
    @property    
    def name(self):
        print('get方法执行了~~~')
        return self._name

    # setter方法的装饰器:@属性名.setter
    @name.setter    
    def name(self , name):
        print('setter方法调用了')
        self._name = name        

    @property
    def age(self):
        return self._age

    @age.setter    
    def age(self , age):
        self._age = age   

        

p = Person('猪八戒',18)

p.name = '孙悟空'
p.age = 28

print(p.name,p.age)

insert image description here

Five, advanced object-oriented

6. Modules and packages

Reference materials:
1. Object-oriented Python (four)
2. Python object-oriented comprehensive and detailed explanation

Guess you like

Origin blog.csdn.net/shammy_feng/article/details/117063531