类和对象

类的函数,继承都是听麻烦一件事情!

什么是OOP变成

OOP就是面对对象编程;面向对象编程,其实就是把遇到的数据,执行操作都定义成类,方便重用。

Enum

枚举类型在Python,也是以的形式存在的。在自定义函数这一章节中,有显示过枚举类型。 VehicleType 类型就是Lukas 全家在旅行当中,定义的高速公路上的车辆类型,有小汽车,有救护车; ExpresswayLocation 类型就是 Lukas 全家在旅行途中,经过的惠深沿海高速的区间段,有深圳段,有惠州段。枚举类型是可以继续扩充的。

'''
Welcome to LearnPython.NET

File Name: PDataType.py
Download from:https://www.learnpython.net/cn/python-code-samples.html
Author: LearnPython.Net
Editor: CoderChiu

'''

from enum import Enum
#定义车辆的类型;
class VehicleType(Enum):
     Car = 1
     Ambulance = 2
#定义路段
class ExpresswayLocation(Enum):
     ShenZhen = 1
     HuiZhou = 2  

如何使用上边定义的 VehicleTypeExpresswayLocation 两个枚举类呢?

def ExpresswaySpeedCheck(nSpeed, enumCarType, enumLocation):
    if enumCarType == VehicleType.Ambulance:
        return True
    else:
        if enumLocation == ExpresswayLocation.ShenZhen:
            return ExpresswaySpeedCheckinShenZhen(nSpeed)
        elif enumLocation == ExpresswayLocation.HuiZhou:
            return ExpresswaySpeedCheckinHuiZhou(nSpeed)
        else:
            return False

枚举类型跟正常的内建类型使用,没啥区别,可以赋值,可以比较;使用枚举了下,主要是增加了代码的可读性,易于理解。

#枚举类型的赋值操作
enumCarType = VehicleType.Car
enumLocation = ExpresswayLocation.ShenZhen

#小汽车当然速度79,运行在深圳,检查是否合法;
print(ExpresswaySpeedCheck(79, enumCarType, enumLocation))

自定义的枚举类型,和程序内建类型,也没啥区别;想一想Lukas旅途中还有数据,可以定义成枚举类型呢?

Class

前面讲的枚举Enum是一种比较简单的类;现在我们要讲的是一种面向对象中刚常用的类。

class ExpresswayCheck:
    def __init__(self, strLocation, nSpeedMin, nSpeedMax):
        self.Location = strLocation
        self.MinSpeed = nSpeedMin
        self.MaxSpeed = nSpeedMax
    
    def showMeTheSpeed(self):
        print(self.Location, "valid speed is ", self.MinSpeed, "~",  self.MaxSpeed, "KM/H.")
        
    def checkSpeed(self, nCurSpeed):
        print(nCurSpeed, " is Valid.")

定义了之后呢,我们如何来使用类。

classEC = ExpresswayCheck("HuiZhou", 60, 120)
classEC.showMeTheSpeed()
classEC.checkSpeed(120)

执行结果:

>>> %Run PDefClass.py
HuiZhou valid speed is  60 ~ 120 KM/H.
120  is Valid.

是不是挺简单的!是不是认为不就是几个变量,和几个函数,合在一起不就是类了,有啥难的!其实现在看到确实如此,但实际工作中,遇到的情况可能比这个稍稍复杂一些!

类的继承

类可以继承的。

Objects

对象就是类的实例。

Last updated