第六周练习 part1 --- 类
Posted lief
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了第六周练习 part1 --- 类相关的知识,希望对你有一定的参考价值。
1 # 类 2 class Role: 3 def __init__(self, name, character, weapon, skills=10, life_value=10000, money=30000, level=99): 4 # 构造函数,在实例化时做一些类的初始化工作 5 self.name = name # [[实例变量]](静态属性)【变量】,作用域是实例本身 6 self.character = character 7 self.weapon = weapon 8 self.life_value = life_value # 私有属性——前面加两个杠,就不能在类的外部直接访问、更改了,类内部的方法仍可以访问 9 self.money = money 10 self.level = level 11 self.skills = skills 12 13 def __del__(self): 14 # 析构函数,做收尾工作 15 print("%s Completely Dead" % self.name) 16 17 class Villan(Role): 18 def kill(self): 19 print("I am Thanos") 20 21 class Avenger(Role): 22 A = "Infinity War" # [[类变量]] 23 ‘‘‘类变量与实例变量 24 类变量存储实例共有的属性,实例变量存储各自特有的属性 25 所以若实例变量中出现了和类变量同名的变量,自然是优先访问实例变量 26 但并不通过将其设置为默认参数来给实例添加属性,因为类变量只需要一份存储空间 27 而实例变量则每次实例化都会占用一次存储空间‘‘‘ 28 29 def show_info(self): 30 # 类的方法、功能(动态属性)【方法】 31 print(‘‘‘Name: %s\nCharacter: %s\nWeapon: %s\nLife_value: %s\nMoney: %s\nSkills: %s\nLevel: %s‘‘‘ 32 % (self.name, self.character, self.weapon, self.life_value, self.money, self.skills, self.level)) 33 34 def aim_at(self, name): 35 print("Aim at %s now" %name) 36 37 def shoot(self): 38 self.money += 10 39 print("Target got shoot") 40 print("%s earned 10 bucks and now he has %s bucks" % (self.name, self.money)) 41 42 def get_shoot(self): 43 self.life_value -= 10 44 print("%s got shoot and his current life value is %s" %(self.name, self.life_value)) 45 46 def gun(self, new_weapon): 47 self.weapon = new_weapon 48 self.money -= 100 49 print("%s costs you 100 bucks and now you have %s bucks left" %(new_weapon, self.money)) 50 51 def __privatefunc(self): # 私有方法,也是在类外部不能调用,只能在内部由别的方法调用 52 pass 53 54 # 实例化过程,得到 Role 的实例 55 # c1 = Avenger(‘Lief‘, ‘GoodMan‘, ‘399式‘) 56 c2 = Avenger(‘Tony‘, ‘IronMan‘, ‘Mark 47‘, money=1000000000) 57 c3 = Avenger(‘Thor‘, ‘ThunderGod‘, ‘StormHammer‘) 58 # c4 = Avenger(‘Peter‘, ‘SpiderMan‘, ‘IronSpiderSuit‘) 59 # c5 = Avenger(‘Banner‘, ‘Hulk‘, ‘HisFists‘, skills=5) 60 # c6 = Avenger(‘Natasha‘, ‘BlackWidow‘, ‘WidowsBite‘, skills=100) 61 # c0 = Villan("Thanos", ‘灭霸‘, "Infinety Gloves") 62 # 63 c2.show_info() 64 # c1.aim_at(‘Tony‘) 65 # c1.shoot() 66 # c2.get_shoot()
以上是关于第六周练习 part1 --- 类的主要内容,如果未能解决你的问题,请参考以下文章