面向对象编程是最有效的软件编写方法之一,编写类时,定义一大类对象都有的通用行为。基于类创建对象时,每个对象都有自动具备这种通用行为,根据需要赋予每个对象独特的个性。
类:抽象描述
对象:具体存在
python里面表达类:class 类名
python里面表达对象:实例化
关键字:class
语法:Class 类名:
属性值
类函数
类名()
语法规范:1、类名的首字母大写,驼峰命名
2、类名需要做到见名知意
class Automobile:
wheel=4
ornaments="方向盘"
chair="真皮"
def white(self):
print("这是辆白色汽车")
def sports(self):
print("这是辆跑车")
上面就是创建了一个汽车的类,只要是这个类的都会具有这些特征的。且具有三个属性值:wheel,ornaments,chair同时的话也是有两个类函数,white、sports。当创建完成实例,那么就默认有上述的三个属性和两个函数使用权限。
创建实例(创建对象),对应语法:实例=类名()
test=Automobile()
实例调用属性:类里面的属性以及方法都只有实例才有权限去调用和使用
class Automobile:
wheel=4
ornaments="方向盘"
chair="真皮"
def white(self):
print("这是辆白色汽车")
def sports(self):
print("这是辆跑车")
test=Automobile()
print(test.ornaments)
----------------打印结果----------------
方向盘
实例调用类函数(类方法):类里面的函数实例只有权限去进行调用
class Automobile:
wheel=4
ornaments="方向盘"
chair="真皮"
def white(self):
print("这是辆白色汽车")
def sports(self):
print("这是辆跑车")
test=Automobile()
test.sports()
test.white()
----------------------打印结果----------------------
这是辆跑车
这是辆白色汽车