Oct-31-2017, 03:55 PM
Hoping to get feedback and help when using Abstract classes. I had an example before, but it probably wasn't the best case for abstract classes. I came up with a new context, and decided to create a small text adventure game.
Questions:
1. Did I archive that goal? It complies and runs, but I've written enough code to know, just because it complies and runs doesn't mean it's the best practice. Have I correctly implemented and used an abstract base class?
2. Is my use of pass in the abstract base class appropriate? Given those methods are implemented in the subclass rather than the base class.
from abc import ABCMeta from abc import abstractmethod class Weapon(metaclass=ABCMeta): def __init__(self, name, damage): self.name = name self.damage = damage @abstractmethod def prepare(self): pass @abstractmethod def attack(self): pass @abstractmethod def cleanup(self): pass def __str__(self): return "Name: {} Damage: {}".format(self.name, self.damage)
from Weapon import Weapon class ChargeGun(Weapon): def __init__(self, name, damage): super().__init__(name, damage) def prepare(self): print("Aiming my Gun"); def attack(self): print("Shooting") def cleanup(self): print("Lowering gun, and turning off laser sight") def charge(self): print("Charging Gun. Please hold..(elevator music playing)")
from Weapon import Weapon class Sword(Weapon): def __init__(self, name, damage): super().__init__(name, damage) def prepare(self): print("Raising my Sword"); def attack(self): print("Attacking enemy with Sword") def cleanup(self): print("Wiping blood from Sword")
from ChargeGun import ChargeGun from Sword import Sword def main(): cg = ChargeGun("Standard ChargeGun",5) sw = Sword("Standard Sword", 3) cg.prepare() sw.prepare() cg.charge() if __name__ == "__main__": main()Goal: Implement an abstract base class, and create subclass to override the methods.
Questions:
1. Did I archive that goal? It complies and runs, but I've written enough code to know, just because it complies and runs doesn't mean it's the best practice. Have I correctly implemented and used an abstract base class?
2. Is my use of pass in the abstract base class appropriate? Given those methods are implemented in the subclass rather than the base class.