Python学习笔记之类和对象

image.png

面向对象编程,是当前比较主流的编程方式。Python同样支持面向对象编程,在面向对象编程中,可以编写表示现实世界中的事物或者情景。在定义类时,需要对现实世界中的对象进行抽象。基于类创建对象时,是对每个现实世界中的对象进行实例化。

创建和使用类

使用类几乎可以模拟任何一样现实世界中的事物,比如我们编写一个通用的汽车类-它表示的不是一辆具体的汽车,而是任何的汽车所共有的特点中抽象出来的。

创建汽车类

每辆汽车都有发动机,有颜色,有排量,可以驾驶,可以刹车,现在我们先根据这些特点来定义一个汽车的类。

语法关键字class

class Car():
    def __init__(self,color,displacement,engine):
        self.color = color
        self.displacement = displacement
        self.engin = engine

    def drive_forward(self):
        print('Moving forward')

    def drive_backward(self):
        print('Moving backward')

    def brake(self):
        print('Braking')

实例化以及调用方法

my_car = Car('yellow','1.6T','Sabb')
print(my_car.color)

my_car.drive_forward()
my_car.drive_backward()
my_car.brake()

继承

语法:class subclass(parentclass)

class TestCar(Car):
    def __init__(self, color, displacement, engine):
        super().__init__(color, displacement, engine)

    def description(self):
        print(self.color + self.displacement + self.engin)

my_testcar = TestCar('Red', '1.8T', 'Audi')
my_testcar.description()

重定义父类的方法

    def drive_backward(self,speed):
        print('Moving back: ' + str(speed))

调用

my_testcar.drive_backward(100)

结语

在程序设计的过程中,面向对象编程的思想可以让代码的组织更加的有条理,也使复杂的项目开发进度更加迅速,在真实的项目中,面向对象的编程设计已经是主流的方法。

附录 - 程序代码

class Car():
    def __init__(self, color, displacement, engine):
        self.color = color
        self.displacement = displacement
        self.engin = engine

    def drive_forward(self):
        print('Moving forward')

    def drive_backward(self):
        print('Moving backward')

    def brake(self):
        print('Braking')

my_car = Car('yellow', '1.6T', 'Sabb')
print(my_car.color)

my_car.drive_forward()
my_car.drive_backward()
my_car.brake()

print('继承')
class TestCar(Car):
    def __init__(self, color, displacement, engine):
        super().__init__(color, displacement, engine)

    def description(self):
        print(self.color + self.displacement + self.engin)

    def drive_backward(self,speed):
        print('Moving back: ' + str(speed))

my_testcar = TestCar('Red', '1.8T', 'Audi')
my_testcar.description()

my_testcar.drive_backward(100)

猜你喜欢

转载自blog.csdn.net/eksbobo/article/details/78825903
今日推荐