Classes and Objects in Python
Welcome to Classes and Objects
Let's dive into a foundational concept in Object-Oriented Programming (OOP): Classes and Objects. If you have already explored OOP concepts in other programming languages or previous units, this might serve as a good reminder. If not, no worries, we'll start from the basics.
What is a Class?
In Python, a class is a blueprint for creating objects, encapsulating data (attributes) and functions (methods) to manipulate that data. Think of a class like a template. For example, consider a Person class, which might have attributes like name and age, and methods like display to showcase this information. The class defines the structure and behavior of the objects that are created from it, but it doesn't consume any memory until instances (objects) are created.
Defining a class doesn't automatically create objects; rather, it establishes a new data type that can be used to create multiple instances or objects. These objects, or instances, are created using the class and can have unique attribute values while sharing the same methods. For instance, Person is the class, and person1 and person2 are two distinct objects created from the Person class. Each object operates independently but follows the shared structure and behavior defined by the class.
Declaring and Defining Classes
In Python, a class is defined using the class keyword. Here's a simple example:
In this snippet, we define a Person class with data members name and age.
Methods
Methods in Python classes are functions that are defined inside the class and are used to manipulate the attributes of an instance or to perform operations related to the object. A method is called on an object and has access to the object’s attributes through the self parameter. All methods in Python should have self as the first parameter to refer to instance attributes and methods from within the method.
For example, consider a display method in the Person class that shows the person's details:
In this example, the display method prints the name and age attributes of the Person object to the console. When you call person.display(), where person is an instance of Person, it invokes the display method and outputs the person’s details. The self parameter in the method ensures that it can access and modify the specific instance's attributes and behaviors.
Methods can also accept additional parameters to perform various operations. Here’s a method to update the age of a Person:
In the update_age method, the new_age parameter is used to update the age attribute of the object. Calling person.update_age(31) changes the age to 31 for the person object.
This modular approach allows you to define functionalities specific to objects, enhancing code reusability and maintainability. By encapsulating behaviors within methods, you ensure that related operations are packaged together, making your code cleaner and easier to manage.
