Python hosting: Host, run, and code Python in the cloud!
Introduction to Python Classes
The landscape of technology has always been evolving, and so has the way we program. In our journey of understanding Python, we encounter the concept of classes. But before we delve into that, let’s trace back a bit. Where did classes originate from?
In the initial stages of computing, programmers only wrote commands or statements to communicate with machines.
To make code more modular and readable, functions were introduced. These are reusable groups of statements that structure the code better.
Enter the world of classes, the heart of object-oriented programming (OOP). With classes, we create objects. These objects have both functions (methods) and variables. A good example would be strings in Python. For instance, a string variable named ‘book’ has methods like
book.lower(). This programming paradigm, where we model real-world objects, is commonly referred to as object-oriented programming.
Let’s further explore this concept.
Recommended Python Course:
Python Programming Bootcamp: Go from zero to hero
Understanding Python Classes
In Python, classes allow us to craft virtual objects. These objects can house both variables (often called attributes) and functions (referred to as methods). For instance, consider the following class:
Here, we have a class
User with an attribute
name and a method
sayHello. We can create instances of this class like so:
james = User("James")
James, David, and Eric are all instances (or objects) derived from the User class.
User class, we’ve also defined a method
sayHello(). That’s why we’re able to call it on each of the objects. The special method
__init__() is termed as the constructor. This is automatically invoked whenever a new object is created. Attributes associated with a class, like
name in this case, are commonly known as class attributes.
Classes also grant us the capability to define methods that modify the internal state (or attributes) of an object. To illustrate this, let’s dive into another example.
Class Attributes and Their Manipulation
Imagine a scenario where we want to model a coffee machine. This machine will have attributes to store the amount of beans and water. We’d also want methods to add or remove beans and water. Here’s how we can model this:
The above class,
CoffeeMachine, has attributes
water. The methods allow us to manipulate these attributes. For instance:
pythonBean = CoffeeMachine("Python Bean", 83, 20)
On running this, we’d get an output like:
Name = Python Bean
This showcases how the internal state of our
pythonBean object changes as we invoke methods on it.