Back to Python
2026-01-178 min read

Object Definitions (Python Programming)

Learn Object Definitions (Python Programming) step by step with clear examples and exercises.

Title: Object Definitions (Python Programming)

Why This Matters

Understanding object definitions is crucial for any Python programmer as it forms the foundation of creating and manipulating data structures in your code. This knowledge is essential for solving complex problems, debugging issues, and preparing for interviews or exams. With a solid grasp of object definitions, you'll be well-equipped to create efficient and reusable code.

Prerequisites

Before diving into object definitions, you should have a basic understanding of:

  1. Python syntax (variables, operators, control structures)
  2. Data structures in Python (lists, tuples, dictionaries, sets)
  3. Basic file handling and exception handling
  4. Understanding the concept of modules and packages

Core Concept

In Python, an object is any entity that you can work with. This includes simple data types like integers and strings, as well as complex objects such as lists, dictionaries, and custom classes.

To create a new object, you use the = operator to assign a value to a variable. For example:

my_integer = 42
my_string = "Hello, World!"
my_list = [1, 2, 3]
my_dict = {"key": "value"}

In this case, we have created five objects: four simple data types (an integer, a string, and two lists) and one complex object (a dictionary). These objects can be manipulated using various Python functions and operators.

Classes and Instances

Beyond simple data types, you can also create custom classes to define your own objects with specific properties and behaviors. A class is a blueprint for creating multiple instances of an object, each with its unique attributes and methods.

Here's an example of defining a simple Person class:

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

def display_info(self):
print(f"Name: {self.name}, Age: {self.age}, Gender: {self.gender}")

Creating an instance of the Person class with name "Alice", age 25, and gender "Female"

my_person = Person("Alice", 25, "Female")

Accessing and modifying attributes of my_person

my_person.age = 26

print(my_person.display_info()) # Output: Name: Alice, Age: 26, Gender: Female


### Magic Methods (Dual Underscore Methods)

Python provides special methods, called magic methods or dual underscore methods, that allow you to customize the behavior of your objects when certain actions are performed on them. For example, the `__str__` method lets you control how an object is displayed as a string.

class Person:

def __init__(self, name):

self.name = name

def __str__(self):

return f"Person({self.name})"

my_person = Person("Alice")

print(my_person) # Output: Person(Alice)

Worked Example

Let's create a simple BankAccount class that has properties for account number, balance, and interest rate. Include methods to deposit, withdraw, and display the account information.

class BankAccount:
def __init__(self, account_number, initial_balance=0, interest_rate=0.01):
self.account_number = account_number
self.balance = initial_balance
self.interest_rate = interest_rate

def deposit(self, amount):
if amount > 0:
self.balance += amount
return True
else:
print("Invalid deposit amount.")
return False

def withdraw(self, amount):
if amount <= self.balance:
self.balance -= amount
return True
else:
print("Insufficient funds.")
return False

def display_info(self):
print(f"Account Number: {self.account_number}")
print(f"Balance: ${self.balance:.2f}")
print(f"Interest Rate: {self.interest_rate * 100}%")

Creating a new BankAccount instance with account number 123456789, initial balance $1000, and interest rate 0.01

my_account = BankAccount(123456789, 1000)

Depositing $500 into my_account

my_account.deposit(500)

print(my_account.display_info()) # Output: Account Number: 123456789, Balance: $1500.00, Interest Rate: 1.00%

Withdrawing $200 from my_account

my_account.withdraw(200)

print(my_account.display_info()) # Output: Account Number: 123456789, Balance: $1300.00, Interest Rate: 1.00%

Common Mistakes

  1. Forgetting to initialize object attributes in the __init__ method
class Person:
def __init__(self, name):
self.name = name

def display_info(self):
print(f"Name: {self.name}")

my_person = Person("Alice")

my_person.age = 25 # This should have been done in the __init__ method


2. Using `=` instead of `==` for comparison

def is_equal(a, b):

if a = b: # Wrong! Should be if a == b:

return True

else:

return False


3. Forgetting to call the parent class's `__init__` method when inheriting from another class

class Child(Person):

def __init__(self, name, age):

self.age = age # This should be done after calling super().__init__()

my_child = Child("Alice", 5)
  1. Using self instead of the correct variable name when initializing attributes in the __init__ method
class Person:
def __init__(self, name):
self.name = name
self.age = age # Should be self.age = age

Practice Questions

  1. Define a Square class that inherits from the Rectangle class and overrides the perimeter method to calculate the perimeter of a square more efficiently.
  2. Create a Circle class with properties for radius, area, and circumference. Include methods to calculate the area and circumference of the circle using Pi (3.14159).
  3. Write a program that defines a custom module called utils with functions for converting temperatures (Fahrenheit to Celsius, Celsius to Fahrenheit) and calculating the factorial of a number. Import this module into your main script and use its functions.
  4. Create a Shape class with properties for type (e.g., "circle", "rectangle", "square") and area. Include methods to calculate the area based on the shape's properties.
  5. Implement a BankAccount class that has properties for account number, balance, and interest rate. Include methods to deposit, withdraw, and display the account information.
  6. Create a Product class with properties for name, price, and quantity in stock. Include methods to update the quantity in stock when an item is sold and to calculate the total cost of multiple items.
  7. Implement a Person class that has properties for first name, last name, age, and gender. Include methods to get the full name (first name + last name), display the person's information, and update the person's age.
  8. Write a program that defines a custom module called math_utils with functions for finding the greatest common divisor (GCD) of two numbers, calculating the Fibonacci sequence up to a given number, and determining whether a number is prime or not. Import this module into your main script and use its functions.
  9. Create a Car class that inherits from the Vehicle class and adds properties for horsepower, transmission type (e.g., manual, automatic), and top speed. Include methods to display the car's information and calculate the car's fuel consumption based on the number of miles driven.
  10. Implement a Database class that has properties for connection details (e.g., host, database name, username, password) and a method to execute SQL queries. Include a method to create a new table in the database with specified columns and data.

FAQ

  1. What is an object in Python?
  • An object is any entity that you can work with in Python, including simple data types like integers and strings, as well as complex objects such as lists, dictionaries, and custom classes.
  1. How do I create a new object in Python?
  • To create a new object, you use the = operator to assign a value to a variable. For example: my_integer = 42. You can also create complex objects like lists, dictionaries, and custom classes using appropriate syntax.
  1. What is a class in Python?
  • A class is a blueprint for creating multiple instances of an object with specific properties and behaviors. You can define your own classes to create custom objects with unique attributes and methods.
  1. How do I import a module in Python?
  • To import a module, you use the import statement followed by the name of the module. For example: import my_module. If you want to import specific functions or classes from the module, use the dot notation (e.g., from my_module import function_name).
  1. What are magic methods in Python?
  • Magic methods, also known as dual underscore methods, allow you to customize the behavior of your objects when certain actions are performed on them. For example, the __str__ method lets you control how an object appears as a string, which can be useful for debugging and displaying objects in user interfaces.
  1. What is inheritance in Python?
  • Inheritance is a mechanism that allows one class (the subclass or derived class) to acquire properties and methods from another class (the superclass or base class). The subclass inherits attributes and methods from the superclass, which can be modified or extended as needed.
  1. What is polymorphism in Python?
  • Polymorphism is a feature that allows objects of different classes to be treated as if they were instances of a common superclass. This means you can write code that works with multiple object types without having to worry about the specific class of each object.
  1. What is encapsulation in Python?
  • Encapsulation is the practice of keeping the internal details and implementation of an object hidden from external users, while providing a public interface for interacting with the object. In Python, this is achieved through the use of private attributes (prefixed with one or two underscores) and accessor (getter) and mutator (setter) methods for managing those attributes.
  1. What is the purpose of the __init__ method in a class?
  • The __init__ method is a special method that gets called automatically when an instance of a class is created. It is used to initialize the object's attributes with initial values or perform any other necessary setup.
  1. What is the purpose of the __str__ method in a class?
  • The __str__ method is a special method that gets called when an object is converted to a string representation (e.g., using the str() function or concatenating the object with a string). It allows you to customize how the object appears as a string, which can be useful for debugging and displaying objects in user interfaces.
  1. What is the purpose of the __repr__ method in a class?
  • The __repr__ method is similar to the __str__ method but provides a more concise and informative representation of an object, often used for debugging purposes. It should return a string that can be used to recreate the object when evaluated.
Object Definitions (Python Programming) | Python | XQA Learn