• Python 类


    1、创建和使用类

      使用类几乎可以模拟任何东西。

    1.1创建Dog类

      根据Dog类创建的每个实例都将存储名字和年龄。我们赋予了每条小狗蹲下sit()和打滚roll_over()的能力

    #!/usr/bin/env python
    
    class Dog:
        """一次模拟小狗的简单尝试"""
    
        def __init__(self,name,age):
            """初始化属性name和age"""
            self.name = name
            self.age = age
    
        def sit(self):
            """模拟小狗被命令时蹲下"""
            print(self.name.title() + " is now sitting!")
    
        def roll_over(self):
            """模拟小狗被命令时打滚"""
            print(self.name.title() + "roll over!")
    
    my_dog = Dog('white',18)
    
    print("My dog name is " + my_dog.name.title() + ".")
    print("My dog is " +str(my_dog.age) + " years old!")
    my_dog.sit()
    my_dog.roll_over()
    
    ================================================
    My dog name is White.
    My dog is 18 years old!
    White is now sitting!
    Whiteroll over!
    

    1.2创建多个实例

    #!/usr/bin/env python
    
    class Dog:
        """一次模拟小狗的简单尝试"""
    
        def __init__(self,name,age):
            """初始化属性name和age"""
            self.name = name
            self.age = age
    
        def sit(self):
            """模拟小狗被命令时蹲下"""
            print(self.name.title() + " is now sitting!")
    
        def roll_over(self):
            """模拟小狗被命令时打滚"""
            print(self.name.title() + "roll over!")
    
    my_dog = Dog('white',18)
    your_dog = Dog('black',19)
    
    
    my_dog.sit()
    my_dog.roll_over()
    your_dog.sit()
    your_dog.roll_over()
    
    ==============================================
    White is now sitting!
    Whiteroll over!
    Black is now sitting!
    Blackroll over!
    

    2、使用类和实例

    ①Car类

    #!/usr/bin/env python
    
    class Car():
        """一次模拟汽车的简单尝试"""
        def __init__(self,make,model,year):
            """初始化描述汽车的属性"""
            self.make = make
            self.model = model
            self.year = year
    
        def get_descriptive_name(self):
            """返回整洁的描述信息"""
            long_name = str(self.year) + ' ' +self.make + ' ' + self.model
            return long_name.title()
    
    my_new_car = Car('audi','a4',2017)
    print(my_new_car.get_descriptive_name())
    
    ===============================================
    2017 Audi A4
    

    ②给属性指定默认值

    #!/usr/bin/env python
    
    class Car():
        """一次模拟汽车的简单尝试"""
        def __init__(self,make,model,year):
            """初始化描述汽车的属性"""
            self.make = make
            self.model = model
            self.year = year
            self.odometer_reading = 0
    
        def get_descriptive_name(self):
            """返回整洁的描述信息"""
            long_name = str(self.year) + ' ' +self.make + ' ' + self.model
            return long_name.title()
    
        def read_odometer(self):
            """打印一条指出汽车里程的信息"""
            print("This car has " +str(self.odometer_reading) + " miles on it.")
    my_new_car = Car('audi','a4',2017)
    print(my_new_car.get_descriptive_name())
    my_new_car.read_odometer()
    
    ============================================
    2017 Audi A4
    This car has 0 miles on it.
    

    ③修改属性的值

      可以以三种不同的方式修改属性的值:直接通过实例进行修改;通过方法进行设置;通过方法进行递增(增加特定的值)

    • 直接修改属性的值

      

    #!/usr/bin/env python
    
    class Car():
        """一次模拟汽车的简单尝试"""
        def __init__(self,make,model,year):
            """初始化描述汽车的属性"""
            self.make = make
            self.model = model
            self.year = year
            self.odometer_reading = 23
    
        def get_descriptive_name(self):
            """返回整洁的描述信息"""
            long_name = str(self.year) + ' ' +self.make + ' ' + self.model
            return long_name.title()
    
        def read_odometer(self):
            """打印一条指出汽车里程的信息"""
            print("This car has " +str(self.odometer_reading) + " miles on it.")
    my_new_car = Car('audi','a4',2017)
    print(my_new_car.get_descriptive_name())
    my_new_car.read_odometer()
    
    ===============================================
    2017 Audi A4
    This car has 23 miles on it.
    
    • 通过方法修改属性的值
    #!/usr/bin/env python
    
    class Car():
        """一次模拟汽车的简单尝试"""
        def __init__(self,make,model,year):
            """初始化描述汽车的属性"""
            self.make = make
            self.model = model
            self.year = year
            self.odometer_reading = 0
    
        def get_descriptive_name(self):
            """返回整洁的描述信息"""
            long_name = str(self.year) + ' ' +self.make + ' ' + self.model
            return long_name.title()
    
        def read_odometer(self):
            """打印一条指出汽车里程的信息"""
            print("This car has " +str(self.odometer_reading) + " miles on it.")
    
        def update_odometer(self,mileage):
            """将里程表读数设置为指定的值"""
            self.odometer_reading = mileage
    
    my_new_car = Car('audi','a4',2017)
    print(my_new_car.get_descriptive_name())
    my_new_car.update_odometer(23)
    my_new_car.read_odometer()
    
    ==============================================
    2017 Audi A4
    This car has 23 miles on it.
    

        对Car类所做的唯一修改是添加了方法update_odometer()。这个方法接受一个里程值,并将其存储到self.odometer_reading中。

    3、继承

      编写类时,并非总是从空白开始。如果你要编写的类时另一个现成类的特殊版本,可使用继承。一个类继承另一个类时,它将自动获得另一个类的所有属性和方法;原有的类称为父类,而新类称为子类。子类继承了其父类的所有属性和方法,同时还可以定义自己的属性和方法。

    #!/usr/bin/env python
    
    class Car():
        """一次模拟汽车的简单尝试"""
        def __init__(self,make,model,year):
            """初始化描述汽车的属性"""
            self.make = make
            self.model = model
            self.year = year
            self.odometer_reading = 0
    
        def get_descriptive_name(self):
            """返回整洁的描述信息"""
            long_name = str(self.year) + ' ' +self.make + ' ' + self.model
            return long_name.title()
    
        def read_odometer(self):
            """打印一条指出汽车里程的信息"""
            print("This car has " +str(self.odometer_reading) + " miles on it.")
    
        def update_odometer(self,mileage):
            if mileage >= self.odometer_reading:
                self.odometer_reading = mileage
            else:
                print("You cant roll back an odometer!")
    
        def increment_odometer(self,miles):
            self.odometer_reading += miles
    
    class ElectricCar(Car):
        """电动车的独特之处"""
        def __init__(self,make,model,year):
            """初始化父辈的属性"""
            super().__init__(make,model,year)
    
    my_tesla = ElectricCar('tesla','model s',2017)
    print(my_tesla.get_descriptive_name())
    
    ==========================================
    2017 Tesla Model S
    

      

    4、导入类

    #!/usr/bin/env python
    
    from car import Car
    
    my_new_car = Car('audi','a4',2017)
    print(my_new_car.get_descriptive_name())
    
    my_new_car.odometer_reading = 23
    my_new_car.read_odometer()
    
    
    =======================================
    2017 Audi A4
    This car has 23 miles on it.
    

    从一个模块中导入多个类:

    from car import Car,ElectricCar

  • 相关阅读:
    Docker 离线安装
    Python迭代器,生成器,装饰器
    docker “no space left on device”问题解决
    docker磁盘空间不足之数据迁移解决方案
    docker常用的命令
    PaddleOCR+OpenCV实现文字识别步骤
    三行Python代码,让你的数据处理脚本快别人4倍
    [转]GitLab安装与启动
    [转]linux下redis开机自启动
    《高性能MySQL》读书笔记(二)
  • 原文地址:https://www.cnblogs.com/caicairui/p/7552897.html
Copyright © 2020-2023  润新知