Detailed explanation of object-oriented in python (on)

Define a class

# 定义一个类
class Dog():
    pass

# 实例化一个类
d1 = Dog()
d2 = Dog()

# 给实例赋予一个属性name
d1.name = '大黄'

print(d1.name)

Add attributes in the __init__() method

# 定义一个类
class Dog():

    def __init__(self,name,height,blood,power):
        self.name = name
        self.height = height
        self.blood = blood
        self.power = power

# 实例化一个类并给属性赋值
d1 = Dog('大黄',0.7,10,3)
d2 = Dog('二黑',0.5,10,4)

# 输出实例的属性值
print d1.name
print d2.name

self and default attributes

Self represents the current instance . When we create an instance, self in the template represents our instance. We can access the properties of the current instance and call the methods of the current instance through self :

# 定义一个模板
class Dog():
    # 构造方法
    def __init__(self,name,height,blood,power):
    	# 此时self代表了我们要定义的实例
        self.name = name
        self.height = height
        self.blood = blood
        self.power = power

# 实例化一个类并给属性赋值
d1 = Dog('大黄',0.7,10,3)
d2 = Dog('二黑',0.5,10,4)

# 输出实例的属性值
print d1.name
print d2.name
  • Default attributes

When we first define the method, there will be default attributes. For example, the blood volume is 10 drops at the beginning, so it is the default attribute. We don’t need to pass a value to it in the method parameters, directly in the method’s Just define it in the attribute:

# 定义一个模板
class Dog():
    # 构造方法
    def __init__(self,name,height,power):
        self.name = name
        self.height = height
        # 设置血量为默认属性,值为10
        self.blood = 10
        self.power = power

# 实例化一个类并给属性赋值
d1 = Dog('大黄',0.7,3)
d2 = Dog('二黑',0.5,4)

# 输出实例的属性值
print d1.name
print d2.name
print d1.blood
print d2.blood

Access attributes and modify attributes

This is quite simple, print output instance attributes, and then re-assign the instance attributes:

# 定义一个模板
class Dog():
    # 构造方法
    def __init__(self,name,height,power):
        self.name = name
        self.height = height
        # 设置血量为默认属性,值为10
        self.blood = 10
        self.power = power

# 实例化一个类并给属性赋值
d1 = Dog('大黄',0.7,3)
d2 = Dog('二黑',0.5,4)

# 输出实例的属性值
print d1.power
# 修改实例的属性
d1.power = 9999
# 输出
print d1.power

Create instance and create multiple instances

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/10/23 16:28
# @Author  : Shadow
# @Site    : 
# @File    : 简单的类.py
# @Software: PyCharm

# 定义一个模板
class Dog():
    # 构造方法
    def __init__(self,name,height,power):
        self.name = name
        self.height = height
        # 设置血量为默认属性,值为10
        self.blood = 10
        self.power = power

# 创建多个实例
d1 = Dog('大黄',0.7,3)
d2 = Dog('二黑',0.5,4)

# 输出实例的属性值
print d1.name
print d2.name

# 用id()输出实例的内存地址
print id(d1)
print id(d2)

How to add and use

Now we want to make Rhubarb Erhei start reporting its own data, so add a method bark():

# 定义一个模板
class Dog():
    # 构造方法
    def __init__(self,name,height,power):
        self.name = name
        self.height = height
        # 设置血量为默认属性,值为10
        self.blood = 10
        self.power = power
    # 添加一个方法bark
    def bark(self):
        print '我是{},身高{},攻击力{},血量{}'.format(self.name,self.height,self.power,self.blood)

# 创建多个实例
d1 = Dog('大黄',0.7,3)
d2 = Dog('二黑',0.5,4)
# 使用构造的方法
d1.bark()
d2.bark()

Just calling is boring, let's construct an attack() method to let them fight!

# 定义一个模板
class Dog():
    # 构造方法
    def __init__(self,name,height,power):
        self.name = name
        self.height = height
        # 设置血量为默认属性,值为10
        self.blood = 10
        self.power = power
    # 添加一个方法bark
    def bark(self):
        print '我是{},身高{},攻击力{},血量{}'.format(self.name,self.height,self.power,self.blood)
    # 再添加一个attack()方法来执行攻击这个行为
    def attack(self,dog):
        dog.blood = dog.blood-self.power
        if dog.blood > 0:
            print '{}的剩余血量为:{}'.format(dog.name,dog.blood)
        else:
            print '{}击杀了{}!'.format(self.name,dog.name)

# 创建多个实例
d1 = Dog('大黄',0.7,3)
d2 = Dog('二黑',0.5,4)

# 修改d1的攻击力
d1.power = 999

# 使用构造的方法
d1.bark()
d2.bark()

# 使用attack()方法让d1攻击d2,并输出d2的状态
d1.attack(d2)

Change properties through methods

That is to define a method that can modify the strength attribute, the minimum blood volume is 0, and there can be no negative values. The modified code:

# -*- coding: gbk -*-


# 定义一个模板
class Dog():
    # 构造方法
    def __init__(self,name,height,power):
        self.name = name
        self.height = height
        # 设置血量为默认属性,值为10
        self.blood = 10
        self.power = power
    # 添加一个方法bark
    def bark(self):
        print '我是{},身高{},攻击力{},血量{}'.format(self.name,self.height,self.power,self.blood)
    # 修改attack方法,在attack中调用reduce_blood方法
    def attack(self,dog):
        dog.reduce_blood = dog.reduce_blood(self.power)
        if dog.blood > 0:
            print '{}的剩余血量为:{}'.format(dog.name,dog.blood)
        else:
            print '{}击杀了{}!'.format(self.name,dog.name)
    # 构造一个可以修改实例属性值的方法reduce_blood
    def reduce_blood(self,reduce_value):
        if reduce_value > self.blood:
            self.blood = 0
        else:
            self.blood = self.blood - reduce_value
            

# 创建多个实例
d1 = Dog('大黄',0.7,3)
d2 = Dog('二黑',0.5,4)

# 使用构造的方法
# d1.bark()

# 通过方法reduce_blood()修改属性
d1.attack(d2)

# 输出详细属性
d2.bark()

Combined training

car

Create a class named Car whose method __init__() sets two attributes: name and brand (brand).
Define a method named show() whose function is to print out the name and brand of the car.
Define a method called run() and print: Car XX is running. Where XX represents the name of the car.
Create an instance named car based on this class, first print its two attributes directly through the attributes, and then call the two methods above.

# -*- coding: gbk -*-

# 创建一个名为Car的对象
class Car:
    
    # 构造__init__方法传值并输出name和brand
    def __init__(self,name,brand):
        self.name = name
        self.brand = brand
    # 构造show方法来输出实例的属性值
    def show(self):
        print self.name
        print self.brand
    # 构造run方法来让汽车跑起来
    def run(self):
        print '{}跑起来了~'.format(self.name)


# 直接输出实例的属性
car = Car('Evo','Mitsubishi')
print car.name,car.brand

# 通过上面两个方法输出实例的属性
car.show()
car.run()
5 cars

Create 5 instances of the class written in exercise 1, and call the show method on each instance.

# -*- coding: gbk -*-

# 创建一个名为Car的对象
class Car:
    
    # 构造__init__方法传值并输出name和brand
    def __init__(self,name,brand):
        self.name = name
        self.brand = brand
    # 构造show方法来输出实例的属性值
    def show(self):
        print self.name
        print self.brand
    # 构造run方法来让汽车跑起来
    def run(self):
        print '{}跑起来了~'.format(self.name)


# 创建5个实例,并对每个实例调用show方法
car1 = Car('Evo','三菱')
car2 = Car('翼豹','斯巴鲁')
car3 = Car('Type-R','丰田')
car4 = Car('C63','奔驰')
car5 = Car('GT-R','日产')

# 调用方法
car1.show()
car2.show()
car3.show()
car4.show()
car5.show()

Pig

Create a class named Pig, which contains attributes name and weight.
Define a method named show() to print the basic information of Pig;
define a method named run() to print:'XX: I have never eaten pork, Let you see the pig run! '.
Create multiple instances representing different pigs, and call the above two methods on each instance.

# -*- coding: gbk -*-

# 创建Pig类
class Pig:
    # 构造__init__方法进行传值
    def __init__(self,name,weight):
        self.name = name
        self.weight = weight
    # 构造show方法打印基本信息
    def show(self):
        print '你好!我是{},我{}kg~'.format(self.name,self.weight)
    # 构造run方法输出题目要求内容
    def run(self):
        print '{}:没吃过猪肉,让你看看猪跑~'.format(self.name)

# 实例化多个对象
pig1 = Pig('佩奇',90)
pig2 = Pig('乔治',60)

# pig1调用两个方法
pig1.show()
pig1.run()

# pig2调用两个方法
pig2.show()
pig2.run()
Number of people

In the Car class for completing exercise 1, add an attribute named number_of_people and set its default value to 0. Add an attribute called max_people, which means there can be at most a few people in the car. Modify the corresponding construction method and pass in the value of max_people.
Add a method called set_people(), which allows you to set the number of people in the car, but cannot exceed the limit of max_people.
Add a method called increase_people(). Each call to this method will increase the number of people in the car by 1, but it cannot exceed the limit of max_people.
Add a method called reduce_people(). Each call to this method will reduce the number of people in the car by 1, but at most it will be reduced to 0.
Create an instance named car based on this class, and print two of them directly through the attributes Properties, and then call the above two methods. ; Print how many people are in the car, then call the above 3 methods multiple times and print the number of people in the car.

# -*- coding: gbk -*-

# 创建一个名为Car的对象
class Car:
    
    # 构造__init__方法传值并输出name和brand
    def __init__(self,name,brand,max_people=5):
        self.name = name
        self.brand = brand
        self.max_people = max_people
        self.number_of_people = 0
        
    # 构造show方法来输出实例的属性值
    def show(self):
        print '{}:当前车内人数为:{}'.format(self.name,self.number_of_people)

    # 构造run方法来让汽车跑起来
    def run(self):
        print '{}跑起来了~'.format(self.name)

    # 构造set_people方法,设置车内初始人数
    def set_people(self,people):
        if people <= self.max_people:
            self.number_of_people = people
        else:
            print '超载啦!'

    # 构造increase_people方法,每次调用车内人数加一
    def increase_people(self):
        if self.number_of_people+1 <= self.max_people:
            self.number_of_people = self.number_of_people+1
        else:
            print '超载啦!'
            
    # 构造reduce_people方法,每次调用车内人数减一
    def reduce_people(self):
        if self.number_of_people-1 >= 0:
            self.number_of_people = self.number_of_people-1
        else:
            print '车里已经没人了!'

# 实例化对象car    
car = Car('Evo','三菱',5)

# 通过属性实例直接打印出属性name和brand
print car.name,car.brand

# 调用题目中要求的方法,并输出车内人数
car.increase_people()
car.reduce_people()
car.show()

# 按照题目要求,多次调用以上3个方法,并打印车内人数
car.set_people(5)
car.reduce_people()
car.increase_people()
car.reduce_people()
car.reduce_people()
car.increase_people()
car.reduce_people()
car.show()
car.set_people(5)
car.reduce_people()
car.increase_people()
car.reduce_people()
car.show()
car.run()

Guess you like

Origin blog.csdn.net/qq_43573676/article/details/108735176