Skip to main content

Introduction to Python Classes and Objects

Python Classes and Objects

Classes are used to create objects, which are instances of those classes.

A class is like a blueprint or template that defines the properties (attributes) and behaviors (methods) that objects of that class will have.

Here's an example that demonstrates the concept of classes and objects:

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def greet(self):
print(f"Hello, my name is {self.name} and I am {self.age} years old.")


# Creating objects of the Person class
person1 = Person("Alice", 25)
person2 = Person("Bob", 30)

# Accessing object attributes
print(person1.name) # Output: Alice
print(person2.age) # Output: 30

# Calling object methods
person1.greet() # Output: Hello, my name is Alice and I am 25 years old.
person2.greet() # Output: Hello, my name is Bob and I am 30 years old.

In this example:

  • We define a class called Person.
  • The class has two attributes, name and age, which are initialized using the special method __init__() (known as the constructor).
  • The __init__() method is called when creating a new object of the class and allows us to set the initial values for the attributes.
  • The Person class also has a method called greet(), which prints a greeting message using the object's name and age attributes.
  • The self parameter is a reference to the object itself and is used to access its attributes and methods.
  • We create two objects, person1 and person2, of the Person class.
  • We can access the attributes of each object using dot notation (object.attribute).
  • We can also call the greet() method on each object to invoke its behavior.

Create a Class

To create a class, use the keyword class:

class MyClass:
x = 5

# Accessing the attribute
print(MyClass.x) # Output: 5

Explanation:

  • We define a class called MyClass using the class keyword.
  • Inside the class, we define a class-level attribute x and set its value to 5.
  • Outside the class, we can access the attribute x using dot notation, such as MyClass.x. In this case, it will output 5.

Create Object

To create an object from a class, you can use the class name followed by parentheses. Here's an example of creating an object from the MyClass class.

class MyClass:
x = 5

# Creating an object of MyClass
my_object = MyClass()

# Accessing the attribute of the object
print(my_object.x) # Output: 5

Explanation:

  • We define a class called MyClass with a class-level attribute x set to 5.
  • To create an object from the MyClass class, we use the class name followed by parentheses (MyClass()). This calls the class's constructor (__init__ method) and initializes the object.
  • We create an object named my_object using the MyClass() syntax.
  • We can access the attribute x of the object using dot notation (my_object.x). In this case, it will output 5, as the object inherits the attribute from the class.

The __init__() Function

The __init__() function is a special method in Python classes that is automatically called when an object is created from a class.

It is commonly known as the constructor method. The primary purpose of __init__() is to initialize the attributes of the object.

Here's an example that demonstrates the init() function:

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

# Creating an object of Person class
person1 = Person("Alice", 25)

# Accessing the attributes of the object
print(person1.name) # Output: Alice
print(person1.age) # Output: 25

Explanation:

  • We define a class called Person with an init() method.
  • The __init__() method takes three parameters: self, name, and age. - The self parameter refers to the instance of the object being created, and the name and age parameters are used to initialize the name and age attributes of the object.
  • Inside the __init__() method, we assign the values of the name and age parameters to the corresponding attributes (self.name and self.age).
  • Outside the class, we create an object named person1 from the Person class, passing the arguments "Alice" and 25 to the constructor.
  • We can access the attributes of person1 using dot notation, such as person1.name and person1.age. In this case, they will output "Alice" and 25, respectively, as the object's attributes have been initialized in the __init__() method.

The __str__() Function

The __str__() function is a special method in Python classes that provides a string representation of an object.

It is invoked when the built-in str() function is called on an object or when the object is used in a string context, such as with the print() function.

Here's an example that demonstrates the __str__() function:

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def __str__(self):
return f"Person(name={self.name}, age={self.age})"

# Creating an object of Person class
person1 = Person("Alice", 25)

# Printing the object using print()
print(person1) # Output: Person(name=Alice, age=25)

# Using the object in a string context
message = "The person is: " + str(person1)
print(message) # Output: The person is: Person(name=Alice, age=25)

Explanation:

  • We define a class called Person with an __init__() method to initialize the attributes (name and age) of the object.
  • We also define the __str__() method, which returns a string representation of the object.
  • Inside the __str__() method, we construct a formatted string using the values of the object's attributes (self.name and self.age).
  • The __str__() method is automatically called when we use the print() function or the str() function on the object. In both cases, it returns the string representation of the object, which is then printed or used as part of another string.
  • In the example, when we print person1, the __str__() method is called, and the formatted string representation is printed: "Person(name=Alice, age=25)".
  • Similarly, when we concatenate person1 with another string, the __str__() method is called, and the resulting string is used in the context: "The person is: Person(name=Alice, age=25)".

Object Methods

Object methods are functions defined within a class that operate on the attributes and behavior of an object.

They are used to perform specific actions or computations associated with the object.

Here's an example that demonstrates object methods in Python:

class Circle:
def __init__(self, radius):
self.radius = radius

def calculate_area(self):
return 3.14 * self.radius ** 2

def calculate_circumference(self):
return 2 * 3.14 * self.radius

# Creating an object of Circle class
circle1 = Circle(5)

# Calling object methods
area = circle1.calculate_area()
circumference = circle1.calculate_circumference()

# Printing the results
print("Area:", area) # Output: Area: 78.5
print("Circumference:", circumference) # Output: Circumference: 31.4

Explanation:

  • We define a class called Circle with an __init__() method to initialize the radius attribute of the object.
  • The Circle class also has two object methods: calculate_area() and calculate_circumference().
  • Both methods accept the self parameter, which represents the object itself. By using self.radius, the methods can access the radius attribute of the object.
  • The calculate_area() method computes and returns the area of the circle based on the formula 3.14 * radius^2.
  • The calculate_circumference() method computes and returns the circumference of the circle based on the formula 2 * 3.14 * radius.
  • Outside the class, we create an object named circle1 of the Circle class, passing the argument 5 to the constructor. We then call the object methods calculate_area() and calculate_circumference() on circle1, storing the results in variables area and circumference.
  • Finally, we print the calculated area and circumference using print() statements.

The self Parameter

The self parameter is a convention used to refer to the instance of the class itself within the class methods.

It is the first parameter of any instance method in a class and is automatically passed when calling the method on an object.

The self parameter allows you to access the attributes and methods of the object from within the class.

Here's an example that demonstrates the use of the self parameter:

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def introduce(self):
print(f"My name is {self.name} and I am {self.age} years old.")

# Creating an object of Person class
person1 = Person("Alice", 25)

# Calling the introduce() method
person1.introduce() # Output: My name is Alice and I am 25 years old.

Explanation:

  • We define a class called Person with an __init__() method and an introduce() method.
  • The __init__() method initializes the attributes name and age of the object using the values passed as arguments.
  • The introduce() method uses the self parameter to access the name and age attributes of the object and prints a formatted introduction string.
  • Outside the class, we create an object named person1 of the Person class, passing the arguments "Alice" and 25 to the constructor.
  • We then call the introduce() method on person1. The self parameter is automatically passed, allowing the method to access the attributes name and age of the object and print the introduction string.

Modify Object Properties

To modify the properties or attributes of an object in Python, you can directly access the attributes using dot notation and assign new values to them.

As an example:

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

# Creating an object of Person class
person1 = Person("Alice", 25)

# Modifying object properties
person1.name = "Bob"
person1.age = 30

# Accessing the modified properties
print(person1.name) # Output: Bob
print(person1.age) # Output: 30

Explanation:

  • We define a class called Person with an __init__() method that initializes the name and age attributes of the object.
  • Outside the class, we create an object named person1 of the Person class, passing the arguments "Alice" and 25 to the constructor.
  • To modify the properties of person1, we can directly access the attributes using dot notation (person1.name and person1.age) and assign new values to them.
  • In the example, we modify the name property of person1 by assigning the value "Bob" to person1.name, and we modify the age property by assigning the value 30 to person1.age.
  • After modifying the properties, we can access and print the modified properties using dot notation as well.

Delete Object Properties

You can delete object properties by using the del statement and specifying the attribute you want to remove.

As an example:

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

# Creating an object of Person class
person1 = Person("Alice", 25)

# Deleting object properties
del person1.name
del person1.age

# Accessing the deleted properties (raises an AttributeError)
print(person1.name) # Raises AttributeError
print(person1.age) # Raises AttributeError

Explanation:

  • We define a class called Person with an __init__() method that initializes the name and age attributes of the object.
  • Outside the class, we create an object named person1 of the Person class, passing the arguments "Alice" and 25 to the constructor.
  • To delete properties from person1, we use the del statement followed by the attribute name (del person1.name and del person1.age).
  • After deleting the properties, if we try to access them using dot notation (person1.name and person1.age), it raises an AttributeError since the properties no longer exist.

Delete Objects

You can delete objects by using the del statement and specifying the object you want to remove.

As an example:

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

# Creating an object of Person class
person1 = Person("Alice", 25)

# Deleting the object
del person1

# Accessing the deleted object (raises a NameError)
print(person1) # Raises NameError

Explanation:

  • We define a class called Person with an __init__() method that initializes the name and age attributes of the object.
  • Outside the class, we create an object named person1 of the Person class, passing the arguments "Alice" and 25 to the constructor.
  • To delete the object person1, we use the del statement followed by the object name (del person1).
  • After deleting the object, if we try to access it (print(person1)), it raises a NameError since the object no longer exists.