In this tutorial, we’ll explore the basics of class definitions in Python. A class is like a template for making specific objects. It outlines the characteristics and actions shared by all objects of that type. Classes help organize code, making it easier to reuse and manage.
How to Begin with Class Definitions in Python
To define a class in Python, you use the class
keyword. The class definition must include the class name and a colon (:
) next to it. The body of the class definition uses indentation and contains the properties and behaviors of the class.
Must Read: How to Create a Class in Python
1. Simple Class Definition
Here is an example of a simple class definition:
Python code:
class Pen:
def __init__(self, make, color):
self.make = make
self.color = color
def write(self):
print(f"The {self.make} pen has {self.color} ink.")
This class defines a Pen object with two properties: make
and color
. It also defines a method called write(), which prints a message to the console.
You can make a Pen class instance by calling the class in the same way you do with a function. For example, the following code creates a fresh Pen object named my_pen:
Python code:
my_pen = Pen("Pilot", "Blue")
You can then access the properties and methods of the my_pen
object using the dot notation. For example, the following code prints the make of the pen to the console:
Python code:
print(my_pen.make)
You can also call the write()
method to make the pen write:
Python code:
my_pen.write()
2. Class Methods
Class methods a.k.a. special methods that belong to the class itself, rather than to individual instances of the class. Their main purpose is to perform operations that are common to all objects of the class, such as creating new objects or validating input.
To define a class method, you use the @classmethod
decorator. For example, the following code defines a class method called create()
, which creates a fresh Pen
object from a given name and breed:
Python code:
class Pen:
@classmethod
def create(cls, make, color):
return cls(make, color)
To call a class method, you use the dot notation and the class name. For example, the following code creates a fresh Pen
object named another_pen
using the create()
class method:
Python code:
another_pen = Pen.create("Hauser", "Green")
3. Class Variables
Class variables are variables that belong to the class itself, rather than to individual instances of the class. They store information that is common to all objects of the class, such as the number of objects created. up to a certain point.
To define a class variable, you use the @classmethod
decorator. For example, the following code defines a class variable called num_pens, which stores the number of Pen
objects that have been created:
Python code:
class Pen:
num_pens = 0
def __init__(self, make, color):
self.make = make
self.color = color
Pen.num_pens += 1
The num_pens class variable is incremented each time a new Pen object is created. To access the num_pens
class variable, you use the dot notation and the class name. For example, the following code prints the number of Pen objects created in the console:
Python code:
print(Pen.num_pens)
Also Read: Python Multiple Inheritance
4. Inheritance
Inheritance is a mechanism that allows new classes to be created by deriving from existing classes. Such classes called the subclass, inherit all of the properties and behaviors of the existing class, called the base class.
To define a subclass, you use the class
keyword and the name of the base class, separated by a colon (:
). For example, the following code defines a subclass of the Pen class called Ballpoint
:
Python code:
class Ballpoint(Pen):
pass
The Ballpoint class inherits all of the properties and behaviors of the Pen class. This means that you can create Ballpoint objects in the same way that you create Pen objects. You can also access the properties and methods of Ballpoint objects in the same way that you access the properties and methods of Pen objects.
5. Polymorphism
Polymorphism is a mechanism that allows objects of different types to respond to the same method call in different ways. For example, the following code defines a method called write()
that can be called on both Pen and Ballpoint objects:
Python code:
class Pen:
def __init__(self, make, color):
self.make = make
self.color = color
def write(self):
print(f"The {self.make} pen has {self.color} ink.")
@classmethod
def create(cls, make, color):
return cls(make, color)
class Ballpoint(Pen):
def write(self):
print(f"The {self.make} Ballpoint pen has {self.color} ink.")
pen = Pen.create("Hauser", "Red")
point = Ballpoint.create("Linc", "Orange")
# Call the write() method on both the pen and the point
pen.write()
point.write()
Output:
The Hauser pen has Red ink.
The Linc Ballpoint pen has Orange ink.
The write()
method is overridden in the Ballpoint
class, so when it is called on a Ballpoint
object, the Ballpoint
version of the method is executed. This is an example of polymorphism.
6. Unique Example Code Snippets
Here is a unique example of a class definition using variables and function names that are short and unique, and do not include words like Alice, Wonderland, city, age, or name:
Python code:
class Fan:
fan_count = 0 # Class variable to keep track of the number of fans
def __init__(self, brand, type):
self.brand = brand
self.type = type
self.is_on = False
Fan.fan_count += 1 # Increment the fan count upon instance creation
def turn_on(self):
if not self.is_on:
self.is_on = True
print(f"The {self.brand} {self.type} fan is now turned on.")
else:
print(f"The {self.brand} {self.type} fan is already on.")
def turn_off(self):
if self.is_on:
self.is_on = False
print(f"The {self.brand} {self.type} fan is now turned off.")
else:
print(f"The {self.brand} {self.type} fan is already off.")
def display_info(self):
print(f"Brand: {self.brand}, Type: {self.type}, Is On: {self.is_on}")
# Create a Fan instance
my_fan = Fan("Dyson", "Tower")
# Turn on the fan
my_fan.turn_on()
# Try to turn on the same fan again
my_fan.turn_on()
# Turn off the fan
my_fan.turn_off()
# Display fan information
my_fan.display_info()
# Output the total number of fans created
print(f"Total number of fans: {Fan.fan_count}")
Output:
The Dyson Tower fan is already on.
The Dyson Tower fan is now turned off.
Brand: Dyson, Type: Tower, Is On: False
Total number of fans: 1
7. Comparing Class Definitions in Python
Method | Description | Most Suitable For |
---|---|---|
Class methods | A class method is owned by the class itself, not by individual class instances. People generally use class methods for tasks that apply universally to all objects of the class, such as creating new objects or checking input validity. | Carrying out operations that all class objects commonly share. |
Class variables | Class variables represent data owned by the class as a whole, not tied to specific instances. They are typically employed to hold shared information across all objects of the class, like the count of created objects. | Storing data that all class objects share in common. |
Inheritance | Inheritance enables the creation of new classes by deriving from existing classes. The subclass, which is the new class, inherits all the properties and behaviors of the base class, which is the existing class. | Creating new classes that adopt the properties and behaviors of an existing class. |
Polymorphism | Polymorphism permits objects of various types to react differently when the same method is invoked. | Enabling objects of various types to react differently when the same method is called. |
Which Method Is the Most Suitable?
The most suitable method to use depends on the specific needs of your program. However, here are some general guidelines:
- Use class methods to perform operations that are common to all objects of the class.
- Use class variables to store information that is common to all objects of the class.
- Use inheritance to create new classes that share the properties and behaviors of an existing class.
- Use polymorphism to allow objects of different types to respond to the same method call in different ways.
Conclusion
Class definitions are a powerful way to organize your code and make it more reusable and maintainable. By using class methods, class variables, inheritance, and polymorphism, you can create complex and sophisticated programs.