欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

类_练习题

程序员文章站 2022-05-19 13:32:07
...

练习1:编写一个学生类,产生一堆学生对象

class Student:
    school = 'Luffycity'
    count = 0

    def __init__(self, name, age, sex):
        self.name = name
        self.age = age
        self.sex = sex
        self.count += 1

    def learn(self):
        print('%s is learning' % self.name)

stu1 = Student('alex', 'male', 38)
stu2 = Student('jinxin', 'female', 78)
stu3 = Student('Egon', 'male', 18)

print(Student.count)
print(stu1.count)
print(stu2.count)
print(stu3.count)
结果输出
0
1
1
1

从以上结果可以看出,如果写成self.count ,他就会变成对象的私有属性,所以说虽然实例化了3次,但是类的count值为0,每个对象的count值为1

以下代码验证

print(stu1.__dict__)
print(stu2.__dict__)
print(stu3.__dict__)

结果为

{'name': 'alex', 'age': 'male', 'sex': 38, 'count': 1}
{'name': 'jinxin', 'age': 'female', 'sex': 78, 'count': 1}
{'name': 'Egon', 'age': 'male', 'sex': 18, 'count': 1}

修改代码

class Student:
    school = 'Luffycity'
    count = 0

    def __init__(self, name, age, sex):
        self.name = name
        self.age = age
        self.sex = sex
        # self.count += 1
        Student.count += 1

    def learn(self):
        print('%s is learning' % self.name)

stu1 = Student('alex', 'male', 38)
stu2 = Student('jinxin', 'female', 78)
stu3 = Student('Egon', 'male', 18)

print(Student.count)
print(stu1.count)
print(stu2.count)
print(stu3.count)
print(stu1.__dict__)
print(stu2.__dict__)
print(stu3.__dict__)

结果为:

3
3
3
3
{'name': 'alex', 'age': 'male', 'sex': 38}
{'name': 'jinxin', 'age': 'female', 'sex': 78}
{'name': 'Egon', 'age': 'male', 'sex': 18}

练习2:模仿王者荣耀定义两个英雄类

要求:

  1. 英雄需要有昵称、攻击力、生命值等属性;
  2. 实例化出两个英雄对象;
  3. 英雄之间可以互殴,被殴打的一方掉血,血量小于0则判定为死亡。
class Hero:
    def __init__(self,nick_name, life_value, aggresivity):
        self.nick_name = nick_name
        self.life_value = life_value
        self.aggresivity = aggresivity

    def attack(self, enemy):
        enemy.life_value -= self.aggresivity


# r1 = Hero('可爱的锐雯雯', 80, 50)
# g1 = Hero('草丛伦', 100, 30)
# print(r1.life_value)
# g1.attack(r1)
# print(r1.life_value)


class Riven(Hero):
    camp = 'Noxus'

    # def __init__(self, nick_name, life_value, aggresivity):
    #     super(Riven, self).__init__(nick_name, life_value, aggresivity)


class Garen(Hero):
    camp = 'Demacia'

    # def __init__(self, nick_name, life_value, aggresivity):
    #     super(Garen, self).__init__(nick_name, life_value, aggresivity)


r1 = Riven('可爱的锐雯雯', 80, 50)
g1 = Garen('草丛伦', 100, 30)
print(r1.life_value)
g1.attack(r1)
print(r1.life_value)
print(r1.camp)
print(g1.camp)

# 通过继承的方式新建类B,让B继承A,B会‘遗传’A的所有属性(数据属性和函数属性),实现代码重用