Ahoy, adventurer! You've learned a great deal about Python so far, but now we've arrived at the enchanted forest of Object-Oriented Programming (OOP). Here, everything is an object, even our brave knight! So, let's don our armor of knowledge and explore this new realm.
Classes and Objects
In the OOP realm, classes are like blueprints. They define the shape and behavior of an object. An object is an instance of a class, just like our brave knight is an instance of the Knight class!
# Class definition
class Knight:
# Initializer / Instance attributes
def __init__(self, name, strength):
self.name = name
self.strength = strength
# Instantiate the Knight class
lancelot = Knight("Lancelot", 15)
In the example above, Knight
is the class, and lancelot
is an object (or instance) of that class.
Attributes and Methods
Classes have attributes (characteristics) and methods (actions). For our Knight class, name
and strength
are attributes, while the attack
method defines a Knight's action.
class Knight:
def __init__(self, name, strength):
self.name = name
self.strength = strength
# Method
def attack(self):
return f'{self.name} attacks with strength {self.strength}!'
lancelot = Knight("Lancelot", 15)
print(lancelot.attack())
Inheritance and Polymorphism
Inheritance lets us create a new class (child) that inherits the attributes and methods of an existing class (parent). It's like our brave knight having a child who inherits their bravery and strength!
Polymorphism lets us use the same method name in child classes but perform different actions. It's like our knight's child choosing to use their bravery and strength in their own unique way!
# Parent class
class Knight:
def __init__(self, name, strength):
self.name = name
self.strength = strength
def attack(self):
return f'{self.name} attacks with strength {self.strength}!'
# Child class
class Archer(Knight):
# Polymorphism in action!
def attack(self):
return f'{self.name} attacks with precision, not strength!'
lancelot = Knight("Lancelot", 15)
robin = Archer("Robin", 5)
print(lancelot.attack())
print(robin.attack())
Encapsulation and Abstraction
Encapsulation is wrapping data (attributes) and methods into a single unit (class). It's like our knight wearing a full suit of armor!
Abstraction is hiding the complex details and showing only the essential features of the object. It's like knowing that our knight can attack, but not needing to know how they learned their skills.
class Knight:
def __init__(self, name, strength):
self.name = name
# Encapsulation: Private attribute
self.__strength = strength
# Abstraction: User doesn't need to know the details of this method
def attack(self):
return f'{self.name} attacks with strength {self.__strength}!'
And thus, we emerge from the enchanted forest, wiser and more knowledgeable about the world of OOP in Python.
Let's continue our journey, adventurer! Next, we'll learn about Python libraries.