This article provides a guide to understanding and using classes in Python. Classes are a fundamental part of Python's Object-Oriented Programming (OOP) paradigm, allowing you to bundle data and functionality together.
A class is a blueprint for creating objects. It defines:
Think of it like a template: Class -> blueprint, Object -> actual instance.
When we call Person("Alicja", 1990, "Polish"), Python creates a new object and automatically calls the __init__ method. The person1 and person2 instances are initialized this way.
The self parameter is a reference to the current instance of the class. A reference is essentially the memory address—the specific location in your computer's RAM—where that object's data is stored. It allows the object to access its own attributes and methods. We don't need to pass it manually; Python handles it for us automatically.
Book class with attributes title, author, and pages. Implement an __init__ method that prints "New book: [title]", and an is_long() method that returns True if pages > 300. Finally, create two instances and print their details.get_detailed_info() method that returns a string formatted as "'Title' by Author, [X] pages".is_long() method to print a message like "This is a long read!" for books with more than 300 pages.update_pages(new_pages) that allows you to change the page count of the book instance.
You can provide default values for parameters in the __init__ method. If a value is not provided when creating an instance, the default value will be used. This makes your classes more flexible and easier to use, as you only need to provide essential information.
Product class where the price attribute has a default value of 0.0. Instantiate one product with a price and another without, then print both.A class attribute is a variable that is shared by all instances of a class. Unlike instance attributes (which are unique to each object), class attributes are defined outside of any methods (usually right at the top of the class). They are accessed using the class name itself or through any instance.
Car class with a class attribute wheels = 4. Instantiate two cars, verify they show 4 wheels, then change Car.wheels to 6 and check both instances to see the shared update.brand and model to the Car class. Create an instance for a "Toyota Corolla".fuel_type = 'Petrol' and demonstrate that all instances access the same value.drive() that prints "The [brand] [model] is now driving on [wheels] wheels."A decorator is a design pattern in Python that allows you to modify the behavior of a function or class without permanently changing its source code. Essentially, a decorator is a function that takes another function as an argument and returns a new function that "wraps" the original one.
This is possible because in Python, functions are first-class objects, meaning they can be passed around as arguments, returned from other functions, and assigned to variables.
We can use built-in decorators like @classmethod or @staticmethod (explained in the next section), or create custom decorators for various purposes such as logging, timing, or authorization.
To modify the behavior of a function using a built-in decorator, it is enough to place the decorator name above the function definition, preceded by @.
In the case of custom decorators, we follow the same approach, as shown in the example below, where we place @log_execution above def greet(name): . However, the decorator must be defined beforehand.
*args and **kwargs require further explanation, but for the purpose of below example it is enough to know that this construction allows all arguments passed to the greet() function to be forwarded to the wrapper() function, and then passed again—in the same form—to the original greet() function. Thanks to this, we can execute greet() from within wrapper() using exactly the same arguments as if greet() were called directly, without a decorator.
The greet() function is called with the argument "Alice". If it were executed without the decorator, only "Hello, Alice" would be printed. However, the @log_execution decorator extends its behavior by printing two additional lines: "Executing greet..." and "greet finished.".
bold_decorator that wraps a function returning a string and adds <b> and </b> tags around it.get_text() that returns "Hello World".cls). Use it when you need to access class-level attributes or create alternative constructors (factory methods).self or cls. It behaves like a regular function but lives inside the class namespace. Use it for utility functions that relate to the class logic but don't need to access its state.Key Difference: A class method can modify class state that applies across all instances; a static method is self-contained and doesn't depend on the class or instance state at all.
Person class, add a @classmethod called from_string(cls, person_str) that parses a string like "Alice,1990,Polish" and returns a new Person instance.@staticmethod called is_valid_citizenship(citizenship) that returns True if the citizenship is in a predefined list of allowed countries.
To use global variables inside a class method, you can simply refer to them by name. However, if you need to modify a global variable, you must use the global keyword within the method.
Variables created inside a function or method (local variables) can only be accessed within that scope. In contrast, attributes assigned to self are instance attributes and are accessible by all instance methods within the class.
APP_MODE set to "development". Then implement a class Application with a method show_mode() that prints the current mode using the global variable. ( Do not pass the mode as a parameter. Access the global variable directly inside the method)visits = 0 and a class Website. Each time the method visit() is called, it should increment the global counter. Add a method show_visits() that prints the total visits.
Method overriding occurs when a child class provides a specific implementation of a method that is already defined in its parent class. This is helpful when you want to change or extend the behavior of a parent method to suit the needs of the child class, allowing for polymorphism.
In this section, this concept is only introduced. For a better understanding, refer to the article Classes: Object-Oriented Programming Paradigms.
Shape class with a method area() that returns 0.Square class that inherits from Shape, takes side in its __init__, and overrides area() to return side * side.Circle class that inherits from Shape, takes radius, and overrides area() using math.pi.super() in a ColoredSquare class (inheriting from Square) to set both side and color during initialization.
Note on super(): We use super() because both the parent and child classes define an __init__ method, and the child's version overrides the parent's. However, if the parent has a method that the child does not redefine, the child inherits it automatically and can call it without super().
A docstring is a string literal that occurs as the first statement in a module, function, class, or method definition. Following PEP 257, docstrings should be enclosed in triple double quotes """. They are essential for documentation and are used by tools like Sphinx, pdoc, and Doxygen to generate external manuals.
__str__: Returns a user-friendly string representation of an object (intended for end-users).__repr__: Returns an unambiguous string representation of an object, ideally matching the command used to create it (intended for developers/debugging).Book class.__str__ method to show a friendly message like "Book: Quo Vadis by Henryk Sienkiewicz - 600 pages".__repr__ method to return a string like "Book(title='Quo Vadis', author='Henryk Sienkiewicz', pages=600)".+48 790-430-860
analysislessons@gmail.com