一、含义
python中一切皆为对象,且python3中类与类型(常见数据类型如列表字典等)是一个概念,类型就是类。
二、实例
#!/usr/bin/env python3 #-*- coding:utf-8 -*- print(type([1,23,4])) # <class 'list'> print(list) class School_student: job = 'student' def study(self): print('studying hard') def relax(self): print('realxing happy') print(School_student) # <class '__main__.School_student'> # 由此可见,列表等数据类型也是类,是特征和技能的结合 li = [1,2,3] # 定义列表(实例化) li2 = [] li2.append(0) # li.append()和li2.append()调用同样的方法,但绑定的对象不同,是不同的绑定方法 li.append(4) # 添加元素 [1, 2, 3, 4],append相当于list类的内置方法 list.append(li,5) # [1, 2, 3, 4, 5] # 与li.append(4)作用相同 print(li)
再比如:
#类型dict就是类dict >>> list <class 'list'> #实例化的到3个对象l1,l2,l3 >>> l1=list() >>> l2=list() >>> l3=list() #三个对象都有绑定方法append,是相同的功能,但内存地址不同 >>> l1.append <built-in method append of list object at 0x10b482b48> >>> l2.append <built-in method append of list object at 0x10b482b88> >>> l3.append <built-in method append of list object at 0x10b482bc8>
#操作绑定方法l1.append(3),就是在往l1添加3,绝对不会将3添加到l2或l3
>>> l1.append(3) # [3]
#调用类list.append(l3,111)等同于l3.append(111)
>>> list.append(l3,111) #等同于l3.append(111) [111]
三、面向对象练习
1、编写一个类,批量生产对象,并统计产生对象的次数
#!/usr/bin/env python3 #-*- coding:utf-8 -*- class Students: country = 'China' # 数据属性为共有的 school = 'helloworld' count = 0 def __init__(self,name,age,sex,major): # 函数属性,是给对象用的 self.name = name self.age = age self.sex = sex self.major = major Students.count += 1 # __init__方法每次被触发就表示产生了一个对象,计数器则自加一次,更改其数据属性 def study(self): print('study everyday') def relax(self): print('relaxing') stu1 = Students('婷子',19,'女','Comic') print(stu1.count) # 1 stu2 = Students('星爷',36,'男','Direct') print(stu2.count) # 2 stu3 = Students('琉星',21,'男','Detective') print(Students.count) # 3 print(stu1.count) # 3 print(Students.__dict__) print(stu1.__dict__) # {'name': '婷子', 'age': 19, 'sex': '女', 'major': 'Comic'} print(stu2.__dict__)
2、 模仿LOL编写两个英雄类,英雄有昵称、攻击力、生命值等属性;实例化出两个英雄对象;
英雄之间要有打斗,被打的一方会掉血,血量小于0判定死亡。
#!/usr/bin/env python3 #-*- coding:utf-8 -*- class Gaylen: camp = 'Desmarcia' def __init__(self,nickname,aggressivity,life_valid): self.nickname = nickname self.aggressivity = aggressivity self.life_valid = life_valid def attack(self,target): target.life_valid -= self.aggressivity if target.life_valid <= 0: print('%s is died'%target.nickname) class Hand_of_Knoxus: camp = 'Desmarcia' def __init__(self,nickname,aggressivity,life_valid): self.nickname = nickname self.aggressivity = aggressivity self.life_valid = life_valid def attack(self,target): target.life_valid -= self.aggressivity if target.life_valid <= 0: print('%s is died'%target.nickname) herol = Gaylen('大盖伦',60,300) hero2 = Hand_of_Knoxus('诺手',70,280) herol.attack(hero2) hero2.attack(herol) hero2.attack(herol) hero2.attack(herol) hero2.attack(herol) hero2.attack(herol) print(herol.life_valid) print(hero2.life_valid)