P

Klassen & OOP

Python Syntax Guide

Objektorientierte Programmierung mit Klassen in Python

Klassen & OOP

Objektorientierte Programmierung mit Klassen in Python

Python klassen & oop (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

Python unterstützt objektorientierte Programmierung mit Klassen, Vererbung und speziellen Methoden. Eigenschaften bieten Getter/Setter-Funktionalität, während Klassen- und statische Methoden auf Klassenebene arbeiten.

Common Use Cases

  • Datenmodellierung
  • Code-Organisation
  • Verhaltensverkapselung
  • Vererbungshierarchien

Related Python Syntax

Master Klassen & OOP in Python

Understanding Klassen & OOP 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 Klassen & OOP effectively in your Python projects.

Key Takeaways

  • Datenmodellierung
  • Code-Organisation
  • Verhaltensverkapselung