Classes in Python
Python supports the use of classes.
What is a class?
A class is a cornerstone of object-oriented programming (OOP).
Using classes helps avoid the repetition of information across multiple objects and is more efficient than traditional procedural programming.
Note: In procedural programming, you need to define the properties for each object individually. With OOP, you create a class with those properties and then associate objects with the class, avoiding the need to define them repeatedly.
Class Inheritance
Inheritance is a powerful feature of object-oriented programming, and Python fully supports it.
When a derived class is linked to a base class, it inherits the behavior of the base class while adding its own functionalities.
How to Create a Class in Python
To define a class in Python, use the following syntax:
class ClassName:
content
A Practical Example
Let's create a class called Person:
- class Person():
- '''Class that represents a person.'''
- def __init__(self, first_name, last_name):
- self.first_name = first_name
- self.last_name = last_name
- def __str__(self):
- return "First Name: " + str(self.first_name) + "\nLast Name: " + str(self.last_name)
This class represents a person.
It consists of two methods:
- __init__ defines the properties of the class's objects (self). In this example, each object of the Person() class has two properties:
- first_name
- last_name
- __str__ returns a string representation of the object assigned to the Person() class.
What are methods? Methods are similar to functions but are defined within a class. Additionally, invoking a method uses a different syntax compared to functions.
How to Associate an Object with a Class
To associate an object with a class, type:
eric = Person("Eric", "Idle")
The first argument ("Eric") is associated with the first property of the Person class, first_name.
The second argument ("Idle") is associated with the second property, last_name.
Next, display the content of the eric variable using the print statement:
print(eric)
The Python interpreter returns this result:
First Name: Eric
Last Name: Idle
The program displays the information according to the class properties.
Specifically, it uses the string representation defined in the class's __str__ method.
The Object Has Inherited the Class Properties
This way, you avoid having to specify properties for each object associated with the class.
How to Access an Object's Properties
You can access an object's individual properties by specifying them as attributes.
The property should be indicated to the right of the object's name, separated by a dot.
object.property
Example
In this example, type the following in the console:
eric.first_name
The Python interpreter reads the variable (eric) and returns only the information associated with the first_name property.
Eric
It does not return other properties.
This way, you can read or modify an object's individual information without affecting other properties.
And so on.