classShip:# Class attributemax_no_flags=3def__init__(self,hp,name,speed):# Instance attributeself.hp=hpself.name=nameself.speed=speed# Methoddefmove(self):print(f"{self.name} is moving at speed {self.speed}.")defstop(self):self.speed=0print(f"{self.name} has stopped.")# Create instancesTitanic=Ship(120,"Titanic",21)Carpathia=Ship(100,"RMS Carpathia",14)# Access class attributesprint(Ship.max_no_flags)print(Titanic.max_no_flags)Ship.max_no_flags=4print(Carpathia.max_no_flags)# Access instance attributesprint(Titanic.name)print(Carpathia.name)# Call methodsTitanic.move()Carpathia.stop()
fromrandomimportrandomclassShip:max_no_flags=3def__init__(self,hp,name,speed):# Instance attributeself.hp=hpself.name=nameself.speed=speeddefmove(self):print(f"{self.name} is moving at speed {self.speed}.")defstop(self):self.speed=0print(f"{self.name} has stopped.")classBattleShip(Ship):def__init__(self,hp,name,speed,max_speed,damage,defense,acc):super().__init__(hp,name,speed)self.max_speed=max_speedself.damage=damageself.defense=defenseself.acc=acc# Overriding the move methoddefmove(self,acceleration=1):ifself.speed<self.max_speed:self.speed+=accelerationself.speed=min(self.speed,self.max_speed)print(f"{self.name} is moving at speed {self.speed}.")defstop(self):self.speed=0print(f"{self.name} has stopped.")# New methoddeffire(self,target):ifrandom()<=self.acc:damage=self.damage-target.defenseprint(f"{self.name} hit {target.name} for {damage} damage.")target.hp-=damageiftarget.hp<=0:print(f"{target.name} has been destroyed.")else:print(f"{self.name} missed {target.name}.")Bismarck=BattleShip(500,"Bismarck",0,30,30,10,0.8)Yamato=BattleShip(650,"Yamato",0,27,41,12,0.6)Bismarck.move(5)Bismarck.fire(Yamato)Yamato.fire(Bismarck)Bismarck.stop()print(type(Bismarck))
classShip:def__init__(self,hp,name,speed):self.__hp=hpself.__name=nameself.__speed=speeddefget_hp(self):returnself.__hpdefset_hp(self,hp):ifhp>0:self.__hp=hpelse:print("HP must be greater than 0.")