Lernziele dieses Kapitels
- You import modules from the Python standard library
- You create your own modules and understand __name__ == '__main__'
- You define classes with attributes and methods
- You build PyBuddy as a class with inheritance
Importing Modules
Python has a huge standard library — ready-made tools for math, random numbers, dates, JSON, and more. You don't have to reinvent the wheel!
import math— Mathematical functionsimport random— Random numbersimport datetime— Date and timefrom math import sqrt— Import only one functionimport random as rnd— Assign an alias
Creating Your Own Modules
Every .py file is a module! You can write functions in one file and import them in other files. The code under if __name__ == '__main__': only runs when the file is executed directly — not when imported.
Classes and Objects
With classes you create your own data types. A class is like a blueprint for objects. __init__ is the constructor — it is called when creating. self references the current object.
Inheritance
With inheritance you create specialized classes that inherit properties and methods from a parent class. This saves code and makes it clearer.
Magic Methods
Magic Methods (or Dunder Methods) begin and end with two underscores. They allow you to customize operators and built-in functions for your classes.
Warm-Up: Your Own Helper Module
Create hilfen.py with 3 functions (e.g. flaeche_rechteck, umfang_kreis, durchschnitt). Import them in main.py and test them.
Hinweis:
Challenge: RPG Character System
Create a class Charakter with name, HP, and level. Create a subclass Heiler with a heilen() method that restores HP.
Hinweis:
PyBuddy Checkpoint: PyBuddy Class
PyBuddy becomes a class! He should have a name, be able to greet the user, and process a command. Use __init__ and methods.
Hinweis:
In League of Legends, every champion has a base class with HP, mana, and position. Each special champion (child class) inherits these properties and adds their own abilities — exactly like the inheritance you just learned!
Zusammenfassung
- import math, random, datetime — use the standard library
- Every .py file is a module with __name__ == '__main__'
- class Name: → Class with __init__ and methods
- Inheritance: class Child(Parent) with super()
- Magic Methods make classes pythonic