Clases y POO
Python syntax guide
Programación orientada a objetos con clases en Python
Clases y POO
Programación orientada a objetos con clases en Python
# Class definition
class Person:
"""A simple Person class"""
# Class variable
species = "Human"
def __init__(self, name, age):
"""Constructor"""
self.name = name
self.age = age
def greet(self):
"""Instance method"""
return f"Hello, I'm {self.name}"
@property
def is_adult(self):
"""Property getter"""
return self.age >= 18
@is_adult.setter
def is_adult(self, value):
"""Property setter"""
if value:
self.age = max(self.age, 18)
else:
self.age = min(self.age, 17)
@classmethod
def create_anonymous(cls):
"""Class method"""
return cls("Anonymous", 0)
@staticmethod
def get_species():
"""Static method"""
return "Human"
# Inheritance
class Employee(Person):
def __init__(self, name, age, job_title, salary):
super().__init__(name, age)
self.job_title = job_title
self.salary = salary
def work(self):
return f"{self.name} is working as {self.job_title}"
# Multiple inheritance
class Manager(Employee):
def __init__(self, name, age, salary, department):
super().__init__(name, age, "Manager", salary)
self.department = department
def manage_team(self):
return f"Managing {self.department} department"
# Usage
person = Person("John", 25)
employee = Employee("Jane", 30, "Developer", 75000)
manager = Manager("Bob", 45, 100000, "Engineering")
print(person.greet()) # Hello, I'm John
print(employee.work()) # Jane is working as Developer
print(manager.manage_team()) # Managing Engineering department
Explanation
Common Use Cases
- Modelado de datos
- Organización del código
- Encapsulación de comportamiento
- Jerarquías de herencia
Related Python Syntax
Variables & Data Types
Python variables and data types
Control Flow
Conditional statements and loops in Python
Functions & Generators
Function definitions and generator functions in Python
Modules & Packages
Importing and organizing code with modules and packages
Exception Handling
Error handling with try/except blocks in Python
Master Clases y POO in Python
Understanding clases y poo is fundamental to writing clean and efficient Python code. This comprehensive guide provides you with practical examples and detailed explanations to help you master this important concept.
Whether you're a beginner learning the basics or an experienced developer looking to refresh your knowledge, our examples cover real-world scenarios and best practices for using clases y poo effectively in your Python projects.
Key Takeaways
- Modelado de datos
- Organización del código
- Encapsulación de comportamiento