
![]() |
@wtf | |
(RPG character system) |
||
1
Replies
12
Views
1 Bookmarks
|
![]() |
@wtf | 13 days |
Inheritance & Polymorphism What is Inheritance? Inheritance lets you create a new class (child) that reuses code from an existing class (parent). This means: - Less repetition - Better code organization - Easy extensions to functionality Basic Inheritance Example class Animal: def __init__(self, name): self.name = name def speak(self): print(fself.name makes a sound.) class Dog(Animal): Dog inherits from Animal def speak(self): print(fself.name says Woof!) class Cat(Animal): def speak(self): print(fself.name says Meow!) Using the Subclasses d = Dog(Bruno) c = Cat(Luna) d.speak() Bruno says Woof! c.speak() Luna says Meow! What is Polymorphism? Polymorphism means different objects can use the same method name, but behave differently. In the example above, Dog and Cat both have a speak() method, but each produces a different output. Mini Project: RPG Character System Lets model a simple RPG system with inheritance and polymorphism: class Character: def __init__(self, name, level): self.name = name self.level = level def attack(self): print(fself.name attacks with a basic strike.) class Warrior(Character): def attack(self): print(fself.name swings a sword with strength level self.level!) class Mage(Character): def attack(self): print(fself.name casts a fireball with power level self.level!) Usage c1 = Warrior(Thor, 5) c2 = Mage(Merlin, 7) c1.attack() Thor swings a sword with strength level 5! c2.attack() Merlin casts a fireball with power level 7! Concepts Practiced: - Inheriting properties from a parent class - Overriding methods for customized behavior - Using the same method name for different outcomes ( |
||


