Classes

Classes are a fundamental part of object-oriented programming (OOP) in Python. They allow you to create your own data types that combine data (attributes) and functionality (methods) into a single structure. By using classes, you can model real-world entities, promote code reusability, and make your programs more organized and modular.

In Python, a class serves as a blueprint for creating objects, encapsulating attributes and behaviors that are common to all instances of that class. Let’s dive into the concepts of classes, objects, and how to use them in Python.

Defining a Class

You define a class using the class keyword followed by the class name. By convention, class names are written in CamelCase.

Basic Syntax:

class ClassName:
    # Class attributes and methods go here
    pass

Example:

class Text:
    pass

# Creating an instance of the Text class
my_text = Text()
print(my_text)  # Output: <__main__.Text object at 0x...>
<__main__.Text object at 0x137e24dd0>

In this example, we defined a simple class named Text and created an instance of it, which is stored in the variable my_text.

Adding Attributes and Methods

Attributes are variables that belong to the class, while methods are functions defined within the class that can manipulate those attributes or perform actions.

To define attributes, you typically do this inside a special method called __init__(), which initializes the object’s attributes when it is created.

Example:

class Text:
    def __init__(self, content):
        self.content = content  # Instance attribute

    def word_count(self):  # Method
        return len(self.content.split())

    def shout(self):  # Another method
        result = self.content.upper()
        result = result.replace(".", "!")
        return result

# Creating an instance of Text
my_text = Text("Hello, World! This is a test.")
print(my_text.word_count())  # Output: 6
print(my_text.shout())  # Output: HELLO, WORLD! THIS IS A TEST!
6
HELLO, WORLD! THIS IS A TEST!

In this example, the Text class has an initializer method __init__() that takes content as a parameter and assigns it to an instance attribute. The word_count() method allows you to get the number of words in the text, the shout() method transforms all letters to upper case and replaces dots by an exclamation mark.

Accessing Attributes and Methods

You can access attributes and methods of a class instance using the dot . notation.

Example:

print(my_text.content)  # Output: Hello, World! This is a test.
Hello, World! This is a test.

In this example, we access the content attribute of my_text using dot notation.

Class vs. Instance Attributes

Attributes defined inside the __init__() method are called instance attributes because they belong to a specific instance of the class. In contrast, class attributes are shared by all instances of the class and are defined directly within the class body.

Example:

class Text:
    language = "English"  # Class attribute

    def __init__(self, content):
        self.content = content  # Instance attribute

# Creating instances
text1 = Text("Hello, World!")
text2 = Text("Bonjour, le monde!")

print(text1.language)  # Output: English
print(text2.language)  # Output: English

# Changing class attribute
Text.language = "French"
print(text1.language)  # Output: French
English
English
French

In this example, we defined a class attribute language that is shared by all instances of the Text class. Changing the class attribute affects all instances.

Inheritance

Inheritance allows you to create a new class that inherits attributes and methods from an existing class. This promotes code reuse and makes it easier to create a hierarchy of classes.

Example:

class Text:
    def __init__(self, content):
        self.content = content

    def word_count(self):
        return len(self.content.split())

class FormattedText(Text):  # Derived class
    def __init__(self, content, format_type):
        super().__init__(content)  # Call the parent class's constructor
        self.format_type = format_type

    def display(self):
        return f"[{self.format_type}] {self.content}"

# Creating instances
my_text = Text("Hello, World!")
formatted_text = FormattedText("Hello, World!", "Bold")

print(my_text.word_count())  # Output: 2
print(formatted_text.display())  # Output: [Bold] Hello, World!
2
[Bold] Hello, World!

In this example, we have a base class Text and a derived class FormattedText. The derived class can extend the functionality of the base class.

Back to top