先来一段代码 表示互殴
class Gailun: country='demaxia' def __init__(self,name,age,life_value,att): self.name=name self.age=age self.life_value=life_value self.att=att def attack(self,enemy): enemy.life_value -= self.att class Riwen: country='nocxus' def __init__(self,name,age,life_value,att): self.name=name self.age=age self.life_value=life_value self.att=att def attack(self,enemy): enemy.life_value-=self.att g1=Gailun('nod','24',1000,100) r1=Riwen('riwen','25',800,200) while True: if g1.life_value>=0: g1.attack(r1) print('riven的生命值是%s'%r1.life_value) r1.attack(g1) print('galn的生命值是%s' % g1.life_value) if r1.life_value<0: print('%s已经阵亡' % r1.name) break else: print('%s已经阵亡,生命值为%s'%(g1.name,g1.life_value)) break
类的创建
#类体定义的代码在类的定义阶段就会运行 class Student: school='oldboy' def learn(self): print('is learning') def choose_course(self): print('is choose') print(Student) #查看 print(Student.school) print(Student.learn) #修改 Student.school='oldboyedu' print(Student.school) #增加 Student.country='China' print(Student.country) #删除 del Student.country # print(Student.country) #调用函数 Student.learn('nod') Student.learn() #如果不传参数会出错
类对象属性的查找
#类的所有数据属性是所有对象共享,所有对象都指向同一个地址 #类定义的函数就是给绑定给对象方法使用 #不同对象就是不同绑定方法 #绑定给谁 就应该由谁来调用 谁来调用就会把谁当做第一个参数传递给对应函数 class Student: school='oldboyedu' def __init__(self,name,age,sex): self.Name=name self.Age=age self.Sex=sex def learn(self): print('%s is learning'%self.Name) def choose_course(self): print('is choose_course') stu1=Student('nod','24','M') stu2=Student('luna','25','W') stu1.learn() stu2.learn()
class Student: school='oldboyedu' def __init__(self,name,age,sex): self.Name=name self.Age=age self.Sex=sex def learn(self): print('is learning') def choose_course(self): print('is choose course') #调用类的过程称之为实例化 #得到一个返回值 即对象 该对象是一个空的stu1 #Stuent.__init__(stu1,'nod','24','M') stu1=Student('nod','24','M') print(stu1.__dict__) #__dict__ 查看自己的名称空间 print(type(stu1)) print(stu1.Name,stu1.Age,stu1.Sex)