1.类的概述
class Role():
name = 'BigBird'
color = 'black'
power = 10
def Run(self):
print('跑')
def Jump(self):
print('跳')
SmallBird = Role()
SmallBird.Run()
SmallBird.Jump()
结果:
D:\study\venv\Scripts\python.exe D:/study/python_code2.py
跑
跳
Process finished with exit code 0
2.类的创建和调用
创建类:
使用类:
属性不固定,不灵活,怎么干?
class Role:
def __init__(self,newname,newcolor,newpower):
self.name = newname
self.color = newcolor
self.power = newpower
self.country = '蜀国'
def Run(self,type):
print(self.name + type + '跑' + str(self.power))
def Jump(self):
print(self.name + '跳' + str(self.power))
zhangfei = Role('BigBird','black',' 18')
zhangfei.Run(' OldMan ride a horse ')
结果:
D:\study\venv\Scripts\python.exe D:/study/python_code3.py
BigBird OldMan ride a horse 跑 18
3.带有默认值的类
位参,放左面(newname);关键数参数放在右面(newcolor,newpower)。
python_code4
class Role:
def __init__(self,newname,newcolor='yellow',newpower='15'):
self.name = newname
self.color = newcolor
self.power = newpower
self.country = 'china'
def Run(self,type):
print(self.name + type + '跑' +str(self.power))
def Jump(self):
print(self.name + '跳' +str(self.power))
zhangfei = Role('黑哥',' black ',' 22')
zhangfei.Run(' behind ')
zhaoyun = Role('zhaoyun')
zhaoyun.Jump()
结果:
D:\study\venv\Scripts\python.exe D:/study/python_code4.py
黑哥 behind 跑 22
zhaoyun跳15
4.调用模块中的类
import python_code4
BigBird = python_code4.Role('BigBird',newpower='23')
print(BigBird.name)
print(BigBird.power)
print(BigBird.country)
结果:
D:\study\venv\Scripts\python.exe D:/study/python_code5.py
黑哥 behind 跑 22
zhaoyun跳15
BigBird
23
china
Process finished with exit code 0