Creating Classes and Objects in Python
In Python, a class is a blueprint for creating objects. Objects are instances of classes and represent real-world entities with attributes (data) and behaviors (methods). This article explains how to define classes and create objects, along with examples.
Defining a Class
A class is defined using the class keyword. Here is a simple example:
class Person:
pass
In this example, a class named Person is defined. It is currently empty and does not contain any attributes or methods.
Creating an Object
To create an object, you call the class as if it were a function:
person1 = Person()
print(type(person1))
This creates an instance of the Person class and stores it in the variable person1. The type function confirms that it is an object of the Person class.
Adding Attributes and Methods
Attributes and methods can be added to a class to define its properties and behavior.
Example 1: A Class with Attributes
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person1 = Person("Alice", 30)
print(f"Name: {person1.name}, Age: {person1.age}")
Here, the __init__ method initializes the name and age attributes when the object is created. The attributes are accessed using the dot operator.
Example 2: A Class with Methods
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
return f"Hello, my name is {self.name}."
person1 = Person("Alice", 30)
print(person1.greet())
The greet method defines a behavior for the Person class. It can be called using the dot operator on an object.
Class Variables vs Instance Variables
Class variables are shared across all instances of a class, while instance variables are unique to each object.
Example 3: Class and Instance Variables
class Person:
species = "Human" # Class variable
def __init__(self, name, age):
self.name = name # Instance variable
self.age = age # Instance variable
person1 = Person("Alice", 30)
person2 = Person("Bob", 25)
print(f"{person1.name} is a {person1.species}.")
print(f"{person2.name} is a {person2.species}.")
In this example, the species attribute is a class variable, shared by all instances of the class. The name and age attributes are instance variables, unique to each object.
Example 4: Modifying Attributes
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person1 = Person("Alice", 30)
print(f"Before: {person1.name}, {person1.age}")
# Modifying attributes
person1.name = "Alicia"
person1.age = 31
print(f"After: {person1.name}, {person1.age}")
Attributes of an object can be modified directly using the dot operator.
Encapsulation
Encapsulation allows you to restrict access to certain attributes or methods by using single or double underscores.
Example 5: Private Attributes
class Person:
def __init__(self, name, age):
self.__name = name # Private attribute
def get_name(self):
return self.__name
person1 = Person("Alice", 30)
print(person1.get_name())
Here, the __name attribute is private and cannot be accessed directly. Instead, a getter method is provided to access it.
Key Points
- Classes are defined using the
classkeyword. - Objects are created by calling the class as if it were a function.
- The
__init__method initializes attributes when an object is created. - Attributes and methods define the properties and behavior of a class.
- Class variables are shared, while instance variables are unique to each object.
- Encapsulation allows you to restrict access to sensitive data.
Conclusion
Understanding how to create classes and objects is fundamental to object-oriented programming in Python. By defining attributes, methods, and using concepts like encapsulation, you can model real-world entities and their behaviors effectively in your code.