1、人狗大战(组合)
class Person:
def __init__(self,name,hp,aggr,sex,money):
self.name=name
self.hp=hp
self.aggr=aggr
self.sex=sex
self.money=money
def atta(self,dog):
dog.hp-=self.aggr
def get_weapon(self,weapon):
if self.money>=weapon.price:
self.money-=weapon.price
self.weapon=weapon
print("购买成功")
self.aggr+=weapon.aggr
else:
print("金币不足,无法购买")
class Dog:
def __init__(self,name,hp,aggr,kind):
self.name=name
self.hp=hp
self.aggr=aggr
self.kind=kind
def bite(self,person):
person.hp-=self.aggr
class Weapon:
def __init__(self,name,aggr,price,count):
self.name=name
self.aggr=aggr
self.price=price
self.count=count
def dazhao(self,dog):
if self.count>0:
dog.hp-=self.aggr*2
self.count-=1
else:
print("大招使用次数已达上限")
pis=Person("pis",100,10,"male",10000)
naix=Dog("naix",600,100,"ghost")
sj=Weapon("圣剑",300,6200,1)
pis.get_weapon(sj)
print(pis.aggr)
pis.atta(naix)
print(naix.hp)
pis.weapon.dazhao(naix)
print(naix.hp)
pis.weapon.dazhao(naix)
2、计算环的面积和周长(组合)
#面向对象编程
import math
class Circle:
def __init__(self,r):
self.radius=r
def area(self):
return math.pi*(self.radius**2)
def perimeter(self):
return math.pi*(2*self.radius)
class Ring:
def __init__(self,r1,r2):
self.outside=Circle(r1)
self.inside=Circle(r2)
def area(self):
return self.outside.area()-self.inside.area()
def perimeter(self):
return self.outside.perimeter()+self.inside.perimeter()
ring=Ring(20,10)
print(ring.area())
print(ring.perimeter())