1.语法规范
关键字:class
语法:
class 类名:
属性值
类函数
类名()----创建实例或者说创建对象
类名:每个单词的首字母大写(驼峰命名法)
如何定义类:所有你认为具有共同属性以及共同特征的,我们都可以划分为一个类
2.编写类
class定义出来的是一个类,类有各种参数(属性)和功能(方法)。
class SuperMan:
# 类属性
age = 30
sex = 'male'
name = 'nick'
# 类方法/类函数
def protect_people(self):
print("我是超人")
def fly_t0_sky(self):
print("我可以飞上天")
3.调用属性以及类方法
#创建对象
person = SuperMan()
#调用属性
print(person.name)----输出:nick
#调用函数
person.protect_people----输出:我是超人
4.类函数调用类属性
class SuperMan:
age = 30
sex = 'male'
name = 'nick'
def protect_people(self):
print("我是超人,我的名字叫{}".format(self.name))
person = SuperMan()
person.protect_people----输出:我是超人,我的名字叫nick
5.类的初始化函数__init__()
class SuperMan:
def __init__(self,age,sex,name):
self.age = age
self.sex = sex
self.name = name
def protect_people(self):
print("我是超人")
person = SuperMan(30,'f','nick')
person.protect_people()----输出:我是超人
print(person.age)----输出:30
总结:创建对象时,python会自动运行初始化函数__init__(),开头和结尾的两个下划线是一种约定,旨在避免python默认方法和普通方法发生名称冲突。
6.类的继承
class Aa:
def __init__(self,name,age):
self.name = name
self.age = age
def en_heng(self):
print(self.name+"今年"+str(self.age)+"岁")
def a_ha(self,grade):
print("马上要上小学{}年级了".format(self.grade))
class Bb(Aa):
pass
Ba("张三",6).en_heng()----输出:张三今年6岁
Ba("张三",6).a_ha(1)----输出:马上要上1年级了
总结:子类继承了父类的属性和方法,可以直接调用
7.重写和拓展
把上述子类Bb改写成如下代码
class Bb(Aa):
def en_heng(self):
print(self.name+"今年"+str(self.age)+"岁,可以打酱油了")
def aoto_test(self,code):
print(self.name"能够做{}自动化测试".format(self.code))
Ba("张三",6).en_heng()----输出:张三几年6岁,可以打酱油了
Ba("张三",6).a_ha(1)----输出:马上要上1年级了
Ba("张三",6).aoto_test('python')----输出:张三能够做python自动化
总结:子类可以重写父类的方法,调用时,用的是重写后的
子类可以拓展父类没有的方法
8.类的多继承
class A:
def add(self,a,b):
print('A类中的加法',a+b)
class B:
def sub(self,a,b):
print('B类中的减法',a-b)
class C(A,B):
pass
C().add(1,2)----输出:类A中的加法 3
C().sub(5,2)----输出:类B中的减法 3
多继承的特点:
顺序继承,例:若B类中也有函数add,那么C调用的时候,会按照顺序优先调用前面父类的同名方法
9.类的超继承
超继承是类方法重写的另一种表现形式,超继承要有父类的特性又要有子类的新特性
class Aa:
def __init__(self,name,age):
self.name = name
self.age = age
def en_heng(self):
print(self.name+"今年"+str(self.age)+"岁")
def a_ha(self,grade):
print("马上要上小学{}年级了".format(self.grade))
class Bb(Aa):
def en_heng(self):
print(self.name+"今年"+str(self.age)+"岁,可以打酱油了")
def aoto_test(self,code):
print(self.name"能够做{}自动化测试".format(self.code))
class Cc(Bb):
def auto_test(self,code):
super(Cc,self).auto_test(code)
print("啦啦啦,我就是很贪婪")
Cc('summer',20).auto_test('python')
输出:
summer能够做python自动化测试
啦啦啦,我就是很贪婪
总结:
超继承既可以有父类方法的特性,又具有子类拓展的新特性
超继承要注意关键字super的用法:super写的是子类的类名,顺着子类的类名找到对应的父类,并调用父类的方法,实现超继承