面向对象简单习题分享

1.(开胃菜)在终端输出如下信息:

小明,10岁,男,上山去砍柴

小明,10岁,男,开车去东北

小明,10岁,男,最爱大保健

老李,90岁,男,上山去砍柴

老李,90岁,男,开车去东北

老李,90岁,男,最爱大保健

 1 class Person:
 2     hobby_lst=['最爱大保健','开车去东北','最爱大保健']
 3     def __init__(self,name,age,sex):
 4         self.name=name
 5         self.age=age
 6         self.sex=sex
 7 xm=Person('小明','10岁','')
 8 ll=Person('老李','90岁','')
 9 lst=[xm,ll]
10 for i in lst:
11     for j in Person.hobby_lst:
12         print(f'{i.name},{i.age},{i.sex},{j}')
最终精简版
 1 C:Python36python3.exe "C:Program FilesJetBrainsPyCharm 2018.1.2helperspydevpydevconsole.py" 55960 55961
 2 import sys; print('Python %s on %s' % (sys.version, sys.platform))
 3 sys.path.extend(['D:\PythonS13', 'D:\pythonS12', 'D:/PythonS13'])
 4 PyDev console: starting.
 5 Python 3.6.3 (v3.6.3:2c5fed8, Oct  3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)] on win32
 6 ##下面的都是在pycharm写好拿过来的,上面都是自动生成的
 7 class Person:
 8     hobby_lst=['最爱大保健','开车去东北','最爱大保健']
 9     def __init__(self,name,age,sex):
10         self.name=name
11         self.age=age
12         self.sex=sex
13 xm=Person('小明','10岁','')
14 ll=Person('老李','90岁','')
15 lst=[xm,ll]
16 for i in range(len(lst)):
17     for j in range(3):
18         print(f'{lst[i].name},{lst[i].age},{lst[i].sex},{lst[i].hobby_lst[j]}')
19         
20 小明,10岁,男,最爱大保健
21 小明,10岁,男,开车去东北
22 小明,10岁,男,最爱大保健
23 老李,90岁,男,最爱大保健
24 老李,90岁,男,开车去东北
25 老李,90岁,男,最爱大保健
在终端输出

2.王者毒药菜鸡版:

创建一个类. 塑造人物,英雄. 名字,血量,攻击力. 让两个英雄对打.

class Hero:
    def __init__(self,*args):
        self.name,self.hp,self.ad=args
    def fight(self,other):
        print(f'{self.name}攻击了{other.name}')
        other.hp-=self.ad
        print(f'{other.name}剩余{other.hp}血量')
Nezha=Hero('哪吒',3000,105)
YuJi=Hero('虞姬',2000,200)
Nezha.fight(YuJi)
YuJi.fight(Nezha)
装逼版,省代码不美观
 1 class Hero:
 2     def __init__(self, name, hp, ad):
 3         self.name = name
 4         self.hp = hp
 5         self.ad = ad
 6 
 7     def fight(self, other):
 8         print('%s攻击了%s' % (self.name, other.name))  # 使用占位符
 9         other.hp -= self.ad
10         print('{}剩余{}血量'.format(other.name, other.hp))  # 使用格式化
11 
12 
13 Nezha = Hero('哪吒', 3000, 105)
14 YuJi = Hero('虞姬', 2000, 200)
15 Nezha.fight(YuJi)
16 YuJi.fight(Nezha)
正常版
原文地址:https://www.cnblogs.com/changwentao/p/9235572.html