定义类

定义一个类,格式如下:

class 类名:
    方法列表

demo:定义一个Car类

# 定义类
class Car:
    color = "黑色"
    wheelNum = 4
    # 方法
    def getCarInfo(self):
        print('车轮子个数:%d, 颜色%s'%(self.wheelNum, self.color))

    def move(self):
        print("车正在移动...")

说明:

  • 定义类时有2种:新式类和经典类,上面的Car为经典类,如果是Car(object)则为新式类
  • 类名的命名规则按照"大驼峰"

新式类和经典类的区别?

1)首先,写法不一样:

class A:
    pass

class B(object):
    pass

2)在多继承中,新式类采用广度优先搜索,而旧式类是采用深度优先搜索。

3)新式类更符合OOP编程思想,统一了python中的类型机制。

results matching ""

    No results matching ""