• Home
  • LLMs
  • Docker
  • Kubernetes
  • Java
  • Python
  • Ubuntu
  • Maven
  • Archived
  • About
Python | Classes
Basic class definition:
Classes are blueprints for creating objects in Python.
They bundle data (attributes) and behavior (methods), enabling object-oriented programming concepts like encapsulation, inheritance, and polymorphism.

  • Defining a class:
    __init__: this constructor method is called automatically when an instance of the class is created.
    self: is a reference to the current instance. It is automatically passed to methods.
    Instance variables: they are variables defined with self and are accessible to all methods in the class and to all instances of the class.


  • Creating an instance:

  • Calling methods:

  • Accessing attributes:

  • Modifying attributes:

  • String representation

  • Using class/static methods/attributes
Property decorators:

Inheritance:
Inheritance allows a class to inherit attributes and methods from a parent class.

  • Defining a subclass:

  • Creating an instance of the subclass:

  • Accessing attributes of the subclass:

  • Calling methods of the subclass:
Method overriding:
Subclasses can override methods from their parent class to provide specialized behavior.

  • Overriding methods from the parent class:

  • Calling override methods of an instance of a subclass:
Modules and imports
  • Creating a module:
    Create a file class_module_1.py that contains the definition of two classes:

  • Import entire module:
    Create a file class_import_1.py that imports the module class_module_1 (class_module_1.py):

  • Import specific classes:
    Create a file class_import_2.py that imports specific classes defined in the module class_module_1 (class_module_1.py):

  • Import all:
    Create a file class_import_3.py that imports all classes defined in the module class_module_1 (class_module_1.py):

  • Module aliases
    Using the keyword as to define an alias for a module.
    Create a file class_import_4.py that imports the module class_module_1 (class_module_1.py) and give it an alias f1:

  • Class aliases:
    Using the keyword as to define an alias for a class.
    Create a file class_import_5.py that imports specific classes defined in the module class_module_1 (class_module_1.py) and give them aliases:
© 2025  mtitek