类的定义

42 阅读1分钟

现实中,一类事物具有相似的特征或行为,人们通常会对这一类事物进行命名以便区分其他事物。

Python使用关键字‘class’来定义一个类


class Car:
    wheels = 4              #定义属性,表示汽车的车轮数量
    def drive(self):        #定义方法,用于实现汽车驾驶的行为
        print('行驶')

还可以用来介绍


class Me:
    姓名 = "cb"
    年龄 = 18
    身高 = 1.60
    id = 5
    def name(self):
        return
    def year(self):
        return
    def high(self):
        return
    def 上课(self):
        print("上python课")

对象的创建和使用


self = Me()
print(self.姓名)
self.上课()