- Author

- Name
- Nelson Silva
- Social
Introduction
Object-Oriented Programming (OOP) is a programming paradigm that uses objects and classes to organize code in a more natural way, representing entities and the actions those entities can perform.
What are Classes and Objects
Classes
A class is a kind of "mold" or "template" for creating objects. It defines the attributes (characteristics) and methods (actions) that its objects will have. You can think of classes as the architectural blueprints of a house.
Objects
An object is an instance of a class. Using the previous analogy, if the class is the architectural blueprint, the object is the actual house built from that blueprint.
How to Work with Classes and Objects in Python
Let's look at a simple example using an Enemy class:
class Enemy:
lives = 5
def attack(self):
print('I was attacked and lost a life.')
self.lives -= 1
def checkLife(self):
if self.lives <= 0:
print('I am dead because I have no more lives.')
else:
print('I am still in combat and have', self.lives, 'lives.')
enemy1 = Enemy()
enemy2 = Enemy()
enemy1.attack()
enemy1.attack()
enemy1.attack()
enemy1.checkLife()
enemy2.checkLife()
Best Practices with OOP
- Encapsulation: Protect internal details and complexity, and expose only what is safe and necessary.
- Inheritance: Avoid code duplication through inheritance, allowing a class to inherit attributes and methods from another class.
- Polymorphism: Allows objects of different classes to be treated as objects of the same class.
Conclusion
Working with classes and objects in Python is fundamental for more complex and well-structured applications. OOP is a powerful tool that makes code more reusable and easier to maintain.