类的使用,对象的使用

一、类的使用

class Student:
    school = 'Luffycity'

    def eat(self):
        print("yes")

    def drink(self):
        print("drink")


# 查看
print(Student.__dict__)

#
Student.teacher = 'gaohui'
print(Student.__dict__)

# 修改
Student.teacher = 'hong'
print(Student.teacher)

# 删除
del Student.teacher
print(Student.__dict__)

 

二、对象的使用

 1 class Student:
 2     room = 'Team'
 3 
 4     def eat(self, x):
 5         print('eating', x)
 6 
 7     def study(self):
 8         print('studying')
 9 
10     def __init__(self, name, age):
11         self.Name = name
12         self.Age = age
13 
14 
15 stu1 = Student('gaohui', 22)
16 stu2 = Student('hong', 22)
17 stu3 = Student('alex', 26)
18 
19 
20 # 特征,类中的特征是对象所共有的
21 
22 #
23 stu1.Name = 'gao'
24 print(stu1.Name, stu1.__dict__)
25 
26 
27 #
28 stu1.Grade = 'middle'
29 print(stu1.Grade, stu1.__dict__)
30 
31 
32 #
33 del stu1.Grade
34 print(stu1.__dict__)
35 
36 
37 #
38 print(stu1.__dict__, stu1.Age, stu1.Name)
39 
40 
41 # 技能  类的函数属性绑定对象,绑定到不同的对象,当对象调用绑定方法时,会把对象当做第一个参数传入,传给self,所以方法的内存空间是不一样的
42 
43 
44 #
45 stu1.eat(1)
46 print(stu1.eat)
47 stu2.eat(2)
48 print(stu2.eat)
49 stu3.eat(3)
50 print(stu3.eat)
51 
52 
53 
54 
55 输出结果为:
56 gao {'Name': 'gao', 'Age': 22}
57 middle {'Name': 'gao', 'Age': 22, 'Grade': 'middle'}
58 {'Name': 'gao', 'Age': 22}
59 {'Name': 'gao', 'Age': 22} 22 gao
60 eating 1
61 <bound method Student.eat of <__main__.Student object at 0x106a02c18>>
62 eating 2
63 <bound method Student.eat of <__main__.Student object at 0x106a02c88>>
64 eating 3
65 <bound method Student.eat of <__main__.Student object at 0x106a02cc0>>

 

 

写一个小实例:

英雄Gailun和Ruiwen各有100生命值,攻击力分别为20,30,每轮各攻击一次,血量等于0为止。

class Hero1(object):

    def __init__(self,name, life, attack):
        self.life = life
        self.attack = attack
        self.name = name

    def attack2(self, arg1):
        arg1.life -= self.attack
        print('%s的生命值为%s' % (arg1.name, arg1.life))


Gailun = Hero('gailun', 100, 20)
Riven = Hero1('ruiwen', 100, 30)

while True:
    Gailun.attack1(Riven)
    Riven.attack2(Gailun)
    if Gailun.life <= 0 or Riven.life <= 0:
        print('Game over')
        break

 

切记:当两个实例分别继承了父类的属性时,此时两个实例中继承的那个属性不能相互公用。 

posted @ 2018-09-14 15:21  辉辉辉辉a  阅读(186)  评论(0编辑  收藏  举报