OOP

Aus Micropython Referenz
Zur Navigation springen Zur Suche springen

Diese Seite ist noch eine Baustelle. Der Inhalt ist nur meine Arbeitsgrundlage [Bearbeiten | Quelltext bearbeiten]

Original: https://medium.com/@ebojacky/classes-in-python-are-very-easy-51c9df53701b

Classes in Python are very easy[Bearbeiten | Quelltext bearbeiten]

Ebo Jackson Ebo Jackson

· Follow

3 min read · Jul 19, 2024 90


Basic Class Structure[Bearbeiten | Quelltext bearbeiten]

A class in Python is defined using the class keyword. Here's a simple example:

class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def bark(self):
        return f"{self.name} says woof!"

__init__ Method:[Bearbeiten | Quelltext bearbeiten]

This is the initializer method that is called when an instance (object) of the class is created. It initializes the attributes of the class. self: This is a reference to the current instance of the class and is used to access variables and methods associated with the object. Creating Instances You can create instances (objects) of the class and use its methods:

my_dog = Dog("Buddy", 3)
print(my_dog.bark())  # Output: Buddy says woof!
print(my_dog.name)    # Output: Buddy
print(my_dog.age)     # Output: 3

Inheritance[Bearbeiten | Quelltext bearbeiten]

Inheritance allows a class to inherit attributes and methods from another class. The class that inherits is called the child class, and the class being inherited from is called the parent class.

class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        pass

class Dog(Animal):
    def __init__(self, name, age):
        super().__init__(name)  # Call the parent class's __init__ method
        self.age = age

    def speak(self):
        return f"{self.name} says woof!"

Inheritance: The Dog class inherits from the Animal class. super(): This function is used to call methods from the parent class. In this example, it calls the __init__ method of the Animal class. Using super() The super() function is particularly useful when you have a hierarchy of classes and you want to ensure that the initialization (or other methods) of the parent class is properly called.

class Puppy(Dog):
    def __init__(self, name, age, toy):
        super().__init__(name, age)  # Call the parent class's __init__ method
        self.toy = toy

    def play(self):
        return f"{self.name} plays with {self.toy}"

Encapsulation[Bearbeiten | Quelltext bearbeiten]

Encapsulation is the concept of restricting access to certain methods and variables. This can be done by prefixing the variable name with an underscore (_) or double underscore (__).

class Dog:
    def __init__(self, name, age):
        self.__name = name  # Private variable
        self.age = age

    def get_name(self):
        return self.__name

    def set_name(self, name):
        self.__name = name

my_dog = Dog("Buddy", 3)
print(my_dog.get_name())  # Output: Buddy
my_dog.set_name("Max")
print(my_dog.get_name())  # Output: Max

Polymorphism[Bearbeiten | Quelltext bearbeiten]

Polymorphism allows methods to be used interchangeably between different classes. It means that different classes can be treated as instances of the same class through inheritance.

class Cat(Animal):
    def __init__(self, name):
        super().__init__(name)

    def speak(self):
        return f"{self.name} says meow!"

animals = [Dog("Buddy", 3), Cat("Whiskers")]

for animal in animals:
    print(animal.speak())
# Output

Buddy says woof!
Whiskers says meow!

Putting It All Together[Bearbeiten | Quelltext bearbeiten]

Here’s a complete example demonstrating the above concepts:

class Animal:
    def __init__(self, name):
        self.name = name
    def speak(self):
        pass

class Dog(Animal):
    def __init__(self, name, age):
        super().__init__(name)
        self.age = age

    def speak(self):
        return f"{self.name} says woof!"

class Cat(Animal):
    def __init__(self, name):
        super().__init__(name)

    def speak(self):
        return f"{self.name} says meow!"

class Puppy(Dog):
    def __init__(self, name, age, toy):
        super().__init__(name, age)
        self.toy = toy

    def play(self):
        return f"{self.name} plays with {self.toy}"

animals = [Dog("Buddy", 3), Cat("Whiskers"), Puppy("Rex", 1, "ball")]

for animal in animals:
    print(animal.speak())
    if isinstance(animal, Puppy):
        print(animal.play())




Links[Bearbeiten | Quelltext bearbeiten]

Navigation[Bearbeiten | Quelltext bearbeiten]

Zurück zur Hauptseite
Zurück zur Python Übersichtseite