Classes in Python

Classes in Python

This article explains classes in Python.

YouTube Video

Classes in Python

In Python, a class is a central concept in object-oriented programming (OOP) that defines a template for organizing data and the methods that operate on that data. Using classes, you can create data structures and encapsulate behaviors related to the data.

Basics of Classes

To define a class in Python, use the class keyword. Below is the structure and usage of a basic class.

 1# Class definition
 2class MyClass:
 3    # Constructor (initialization method)
 4    def __init__(self, attribute):
 5        self.attribute = attribute
 6
 7    # Method (member function)
 8    def display_attribute(self):
 9        print(self.attribute)
10
11# Creating an object
12obj = MyClass("Hello, World!")
13obj.display_attribute()  # Outputs "Hello, World!"

Components of a Class

Attributes

Attributes of a class refer to the data or state held by an object. In the example above, attribute is an instance attribute.

Methods

Methods are functions defined within a class that specify operations on an object. For instance, the display_attribute method shown above.

Constructor

The __init__ method is called the constructor and is executed when an object is created. It initializes the instance.

Creating and Managing Objects

Creating an object from a class is known as instantiation. In the example above, MyClass is instantiated to create obj. With the created object, you can call methods defined in the class or access attributes.

Inheritance

Classes support inheritance, allowing attributes and methods to be inherited from other classes (parent or base classes). A new class (subclass) can extend its parent class to add functionality.

 1# Parent class
 2class Animal:
 3    def speak(self):
 4        print("Some sound")
 5
 6# Child class
 7class Dog(Animal):
 8    def speak(self):
 9        print("Bark!")
10
11# Instantiation and method call
12dog = Dog()
13dog.speak()  # Outputs "Bark!"

In this way, Python classes are a powerful means of logically associating data and procedures. Other elements of object-oriented programming, such as polymorphism and encapsulation, can also be implemented through classes.

Modules in Python

A module in Python is a unit for organizing and reusing Python code. A module is a file containing Python code, and the functions, classes, variables, etc., within it can be imported and used by other Python code. By using modules, code reusability is improved, and programs become more organized and easier to maintain.

Creating a Module

To create a module, you just need to save a file containing Python code. For example, saving a file with the following content as my_module.py makes it a module.

1def greet(name):
2    return f"Hello, {name}!"
3
4pi = 3.14159

Importing a Module

To use a created module in another file, you use the import statement.

1import my_module
2
3# Using functions and variables from my_module
4print(my_module.greet("Alice"))
5print(my_module.pi)

You can also import specific functions or variables.

1from my_module import greet, pi
2
3# Names can be used directly.
4print(greet("Bob"))
5print(pi)

Module Aliases

You can assign an alias when importing a module. This makes it easier to access the module while writing code.

1import my_module as mm
2
3print(mm.greet("Charlie"))
4print(mm.pi)

Standard Library Modules

Python provides a wide range of built-in standard library modules. You can import and use modules such as the math module or the os module.

1import math
2
3print(math.sqrt(16))
4print(math.pi)

Packages

A package is a collection of multiple modules organized in a directory structure. Using packages allows for better organization of more code and supports large-scale applications.

Leveraging modules and packages in Python allows you to write more efficient and organized programs.

You can follow along with the above article using Visual Studio Code on our YouTube channel. Please also check out the YouTube channel.

YouTube Video