Skip to content
Cover image for: Understanding Python Classes & Objects
#pythonBeginner

Understanding Python Classes & Objects

May 4, 2026
Updated May 14, 2026
30 min read

AI Insights

Powered by GPT-4o-mini

Verified Context: understanding-python-classes-objects

Master Python OOP from fundamentals to design patterns. Learn class and object creation, the __init__ constructor method, self parameter mechanics, instance vs class attributes, @classmethod and @staticmethod, magic methods (__str__, __repr__, __len__, __add__, __eq__), the @property decorator for computed attributes with getter/setter patterns, name mangling for encapsulation, and practical OOP with Rectangle class and a complete Bank Account system example.

Quick Summary

Give the complete code for the BankAccount class.

Python list object attempting string method call raises AttributeError

Explanation

  • The code creates a list object L containing integers [1,2,3] which is a mutable sequence type
  • When calling L.upper() the code attempts to invoke a string method on a list object
  • This raises an AttributeError because lists don't have an upper() method - only string objects do
  • The error occurs at runtime when the interpreter tries to find the upper method in the list's class hierarchy
  • This demonstrates Python's dynamic typing where method calls are resolved at runtime based on object types
python

Output

text

This code attempts to modify a string by appending a character to it.

Explanation

  • Strings in Python are immutable, meaning they cannot be changed after creation.
  • The code tries to use the append method, which is not applicable to string objects.
  • To concatenate a character to a string, the + operator should be used instead.
  • The correct approach would be s = s + 'x' to create a new string with the appended character.
  • This code will raise an AttributeError due to the incorrect method call on a string.
python

Understanding the Object-Oriented Nature of Python Programming

Explanation

  • The comment emphasizes that in Python, every entity is treated as an object, including functions, classes, and data types.
  • This object-oriented approach allows for encapsulation, inheritance, and polymorphism, making code more modular and reusable.
  • It highlights Python's flexibility, as developers can define their own classes and create custom objects.
  • Understanding this concept is crucial for leveraging Python's capabilities effectively in software development.
python

This code snippet demonstrates how to check the type of a Python list.

Explanation

  • A list L is created containing three integer elements: 1, 2, and 3.
  • The print function is used to output the type of the variable L.
  • The type() function returns the data type of the object passed to it, which in this case is a list.
  • The output will confirm that L is of type <class 'list'>.
python

Output

text

Understanding the usage of the upper method in Python class instances

Explanation

  • The upper() method is called on an instance of a class, L, which is expected to be a string or similar datatype.
  • This method converts all lowercase letters in the string to uppercase, returning a new string.
  • In Python, all data types are implemented as classes, allowing for object-oriented programming principles.
  • The snippet illustrates how methods are associated with class instances, demonstrating encapsulation in Python.
python

Output

text

Creating and initializing a list object in Python

Explanation

  • The code demonstrates the syntax for creating an instance of a class in Python, specifically a list.
  • L = list() initializes an empty list and assigns it to the variable L.
  • The print(L) statement outputs the current state of the list, which is empty at this point.
  • This snippet illustrates basic object-oriented programming concepts in Python by showing how to instantiate built-in types.
python

Output

text

This code initializes an empty string and prints it to the console.

Explanation

  • The variable s is created and initialized as an empty string using str().
  • The print(s) statement outputs the value of s, which is currently an empty string.
  • This code demonstrates basic string initialization and output in Python.
  • It can be useful for understanding how to work with string variables in Python.
python

A Python ATM Class Implementation for Managing User Accounts and Transactions

Explanation

  • Defines an Atm class that simulates an ATM system with functionalities like creating and changing a PIN, checking balance, and withdrawing money.
  • The __init__ method initializes the ATM object with default values for pin and balance, and automatically executes upon object creation.
  • The menu method presents a user interface for selecting various operations, directing the flow based on user input.
  • Each operation (creating a PIN, changing a PIN, checking balance, and withdrawing) is handled by dedicated methods that validate user input and update the account state accordingly.
  • The program loops back to the menu after each operation, allowing continuous interaction until the user decides to exit.
python

Instantiating an ATM object in Python for banking operations

Explanation

  • The code creates an instance of the Atm class, which likely encapsulates functionality related to automated teller machine operations.
  • The variable obj now holds a reference to this newly created Atm object, allowing access to its methods and properties.
  • This instantiation is essential for performing actions such as checking balances, withdrawing cash, or depositing funds through the ATM interface.
python

Output

text

Determine the memory address of an object in Python using the id() function

Explanation

  • The id() function returns the unique identifier for an object, which is its memory address.
  • In this snippet, obj is passed to the id() function to retrieve its memory address.
  • The comment indicates that self and obj refer to the same object, implying they share the same memory address.
  • This can be useful for debugging or understanding object references in Python.
python

Output

text

Demonstrating unique object identities in Python using ATM class instances

Explanation

  • Two instances of the Atm class are created, named obj1 and obj2.
  • The id() function is called on each object to retrieve their unique memory addresses.
  • The output will show that obj1 and obj2 have different IDs, confirming they are distinct objects in memory.
  • This illustrates the concept of object identity in Python, where each instance has its own unique identifier.
python

Output

text

This code snippet demonstrates the use of an object to manage a pin and balance with a method to change the pin.

Explanation

  • The obj represents an instance of a class that likely manages financial or secure data.
  • obj.pin is an attribute that stores the current pin associated with the object.
  • obj.balance is an attribute that holds the current balance, possibly for a bank account or similar financial entity.
  • obj.change_pin() is a method that allows the user to update or change the current pin, indicating a focus on security.
python

Output

text

Distinguishing between built-in functions and object methods in Python programming

Explanation

  • len() is a built-in function that operates on objects from outside their class context, taking the list as an argument
  • append() is a method that belongs to the list class and is called directly on list instances using dot notation
  • Functions are standalone operations that require objects as parameters, while methods are behaviors specific to particular object types
  • This distinction demonstrates how Python provides both generic functions and class-specific methods for working with data structures
  • The syntax difference (function call vs method call) helps identify whether an operation is generic or object-oriented in nature
python

Creating a Python class instance with initialization and constructor behavior

Explanation

  • The code defines a class named Temp that contains an init method which executes when a new object is created
  • The init method prints 'hello' to the console whenever the class is instantiated
  • When obj = Temp() is executed, it creates a new instance of the Temp class
  • The constructor automatically calls the init method, triggering the print statement before the object reference is assigned to obj
  • This demonstrates basic object-oriented programming concepts including class definition, instantiation, and constructor execution in Python
python

Output

text

This code snippet performs a multiplication of two fractions and returns the result.

Explanation

  • The code calculates the product of the fractions 3/4 and 1/2.
  • It uses the standard arithmetic operation of multiplication for fractions.
  • The result of the operation is 3/8, which is the simplified form of the product.
  • This operation can be useful in scenarios involving fractional calculations in mathematics or programming.
python

Output

text

A Python class for representing and performing arithmetic operations on fractions

Explanation

  • Defines a Fraction class with a parameterized constructor to initialize the numerator and denominator.
  • Implements string representation using the __str__ magic method for easy printing of fraction objects.
  • Supports addition, subtraction, multiplication, and division of fractions through the __add__, __sub__, __mul__, and __truediv__ magic methods, respectively.
  • Each arithmetic operation returns a new fraction in string format, calculated based on the rules of fraction arithmetic.
  • Includes a method convert_to_decimal to convert the fraction to its decimal representation.
python

Creating a default Fraction object in Python using the fractions module

Explanation

  • The code initializes a new instance of the Fraction class from the fractions module.
  • By default, this instance represents the fraction 0/1, which is equivalent to zero.
  • The Fraction class is useful for performing arithmetic with rational numbers while maintaining precision.
  • This code snippet does not require any parameters, making it straightforward to create a basic fraction object.
python

Output

text

Creating Fraction Objects to Represent Rational Numbers in Python

Explanation

  • The code imports the Fraction class from the fractions module, which allows for the representation of rational numbers as fractions.
  • fr1 is initialized as a fraction representing one-half (1/2).
  • fr2 is initialized as a fraction representing three-quarters (3/4).
  • These fraction objects can be used for arithmetic operations, comparisons, and other mathematical functions while maintaining precision.
python

This code snippet outputs the values of two variables to the console.

Explanation

  • The print() function is used to display the values of the variables fr1 and fr2.
  • Each call to print() will output the current value of the specified variable to the standard output (usually the console).
  • If fr1 and fr2 are not defined prior to this snippet, it will raise a NameError.
  • This code is useful for debugging or verifying the contents of these variables during execution.
python

Output

text

Performing arithmetic operations on two fractions in Python

Explanation

  • The code snippet demonstrates basic arithmetic operations (addition, subtraction, multiplication, and division) between two fraction objects, fr1 and fr2.
  • Each operation is executed using the respective arithmetic operator, and the results are printed directly to the console.
  • The convert_to_decimal() method is called on both fraction objects to convert them into decimal format for easier interpretation.
  • This snippet assumes that fr1 and fr2 are instances of a fraction class that supports these operations and methods.
python

Output

text

Creating and printing a fraction using Python's Fraction class

Explanation

  • The code imports the Fraction class from the fractions module, which allows for precise representation of rational numbers.
  • A fraction object fr3 is created with a numerator of 5 and a denominator of 6.
  • The print function outputs the string representation of the fraction, which in this case will display as 5/6.
  • This demonstrates how to work with fractions in Python, ensuring accurate arithmetic operations without floating-point errors.
python

Output

text

This code snippet sums three fractions and prints the result.

Explanation

  • The code uses the print function to output the result of adding three fractions: fr1, fr2, and fr3.
  • Each fraction variable (fr1, fr2, fr3) is expected to be defined previously in the code.
  • The addition operation combines the values of these fractions, which should be compatible types (e.g., Fraction objects from the fractions module).
  • The result is displayed in the console, allowing the user to see the total of the three fractions.
python

Output

text

A Python class for representing and manipulating fractions with arithmetic operations

Explanation

  • Defines a Fraction class that encapsulates the properties of a fraction with a numerator and denominator.
  • Implements a parameterized constructor to initialize the fraction's numerator (num) and denominator (den).
  • Overrides the __str__ method to provide a string representation of the fraction in the format "numerator/denominator".
  • Implements arithmetic operations (+, -, *, /) using magic methods to allow intuitive usage of fractions with standard operators.
  • Includes a method convert_to_decimal to convert the fraction to its decimal representation by dividing the numerator by the denominator.
python

This code snippet demonstrates the addition of multiple fractions using Python's Fraction class.

Explanation

  • The Fraction class from the fractions module is used to create rational number objects.
  • Three fractions are instantiated: fr1 as 1/2, fr2 as 3/4, and fr3 as 5/6.
  • The print function outputs the result of adding these three fractions together.
  • The addition operation automatically handles the calculation of a common denominator and simplifies the result.
python

Output

text

This code snippet demonstrates the addition of multiple fractions using Python's Fraction class.

Explanation

  • The Fraction class from the fractions module is used to create rational number objects.
  • Four fractions are instantiated: 1/2, 3/4, 5/6, and 4/5.
  • The code adds these fractions together using the + operator, which automatically handles the arithmetic of fractions.
  • The result of the addition is printed to the console, displaying the sum as a simplified fraction.
python

Output

text

##Q-1: Rectangle Class

  1. Write a Rectangle class in Python language, allowing you to build a rectangle with length and width attributes.

  2. Create a Perimeter() method to calculate the perimeter of the rectangle and a Area() method to calculate the area of ​​the rectangle.

  3. Create a method display() that display the length, width, perimeter and area of an object created using an instantiation on rectangle class.

Eg. After making above classes and methods, on executing below code:-

text

Output:

text

This Python code defines a Rectangle class that calculates and displays its dimensions, perimeter, and area.

Explanation

  • The Rectangle class initializes with length and width, storing them as private attributes.
  • It includes private methods __perimeter and __area to calculate the perimeter and area of the rectangle, respectively.
  • The display method prints the rectangle's length, width, perimeter, and area to the console.
  • An instance of the Rectangle class is created with specified dimensions, and the display method is called to show the results.
python

Output

text

##Q-2: Bank Class

  1. Create a Python class called BankAccount which represents a bank account, having as attributes: accountNumber (numeric type), name (name of the account owner as string type), balance.
  2. Create a constructor with parameters: accountNumber, name, balance.
  3. Create a Deposit() method which manages the deposit actions.
  4. Create a Withdrawal() method which manages withdrawals actions.
  5. Create an bankFees() method to apply the bank fees with a percentage of 5% of the balance account.
  6. Create a display() method to display account details. Give the complete code for the BankAccount class.

Eg. After making above classes and methods, on executing below code:-

text

Output:

text

A Python class for managing bank account operations with encapsulation

Explanation

  • The Bank class encapsulates account details such as name, account number, and balance using private attributes.
  • The __init__ method initializes the account with the provided name, account number, and balance.
  • The display method prints the account details, including account number, name, and current balance.
  • The deposit method increases the account balance by a specified amount.
  • The withdrawl method checks for sufficient funds before deducting the requested amount and applies a bank fee calculated by the private method __bankFees.
python

Output

text

##Q-3:Computation class

  1. Create a Computation class with a default constructor (without parameters) allowing to perform various calculations on integers numbers.

  2. Create a method called Factorial() which allows to calculate the factorial of an integer n. Integer n as parameter for this method

  3. Create a method called naturalSum() allowing to calculate the sum of the first n integers 1 + 2 + 3 + .. + n. Integer n as parameter for this method.

  4. Create a method called testPrime() in the Calculation class to test the primality of a given integer n, n is Prime or Not? Integer n as parameter for this method.

  5. Create a method called testPrims() allowing to test if two numbers are prime between them. Two integers are prime to one another if they have only 1 as their common divisor. Eg. 4 and 9 are prime to each other.

  6. Create a tableMult() method which creates and displays the multiplication table of a given integer. Then create an allTablesMult() method to display all the integer multiplication tables 1, 2, 3, ..., 9.

  7. Create a static listDiv() method that gets all the divisors of a given integer on new list called Ldiv. Create another listDivPrim() method that gets all the prime divisors of a given integer.

A comprehensive Python class for mathematical computations including factorial, sums, primality tests, and multiplication tables.

Explanation

  • The Computation class encapsulates various mathematical functions such as calculating factorials, summing natural numbers, and testing for primality.
  • The factorial method computes the factorial of a given number n using a loop.
  • The naturalSum method returns the sum of the first n natural numbers by iterating through a range and accumulating the sum.
  • The testPrime method checks if a number is prime by counting its divisors and returning true if there are exactly two.
  • The testPrims method determines if two integers are co-prime by counting their common divisors and printing the result.
  • Additional methods include generating multiplication tables, listing divisors, and identifying prime divisors of a given integer.
python

Output

text

##Q-4: Build flashcard using class in Python.

Build a flashcard using class in python. A flashcard is a card having information on both sides, which can be used as an aid in memoization. Flashcards usually have a question on one side and an answer on the other.

Example 1:

Approach:

  • Create a class named FlashCard.
  • Initialize dictionary fruits using init() method. Here you have to define fruit name as key and it's color as value. E.g., {"Banana": "yellow", "Strawberries": "pink"}
  • Now randomly choose a pair from fruits by using random module and store the key in variable fruit and value in variable color.
  • Now prompt the user to answer the color of the randomly chosen fruit.
  • If correct print correct else print wrong.

Output:

bash

Create an interactive fruit color quiz using Python classes and randomization

Explanation

  • The FlashCard class initializes a dictionary of fruits and their corresponding colors.
  • The quiz method randomly selects a fruit and prompts the user to guess its color.
  • User input is compared to the correct color, providing feedback on whether the answer is correct or incorrect.
  • After each question, the user can choose to play again or exit the quiz by entering 0 or 1, respectively.
  • The program starts by welcoming the user and instantiating the FlashCard class to begin the quiz.
python

Output

text

Q-5: Problem 5 based on OOP Python.

TechWorld, a technology training center, wants to allocate courses for instructors. An instructor is identified by name, technology skills, experience and average feedback. An instructor is allocated a course, if he/she satisfies the below two conditions:

  • eligibility criteria:
    • if experience is more than 3 years, average feedback should be 4.5 or more
    • if experience is 3 years or less, average feedback should be 4 or more
  • he/she should posses the technology skill for the course

Identify the class name and attributes to represent instructors. Write a Python program to implement the class chosen with its attributes and methods.

Note:

  • Consider all instance variables to be private and methods to be public.
  • An instructor may have multiple technology skills, so consider instance variable, technology_skill to be a list.
  • check_eligibility(): Return true if eligibility criteria is satisfied by the instructor. Else, return false
  • allocate_course(technology): Return true if the course which requires the given technology can be allocated to the instructor. Else, return false.

Represent a few objects of the class, initialize instance variables using setter methods, invoke appropriate methods and test your program.

This Python class evaluates instructor eligibility and course allocation based on experience and feedback.

Explanation

  • The Instructor class initializes with attributes for name, technology expertise, experience, and feedback score.
  • The check_eligibility method determines if an instructor is eligible based on their experience (greater than 3 years) and feedback score (at least 4.5).
  • The allocate_course method checks if the instructor is eligible and whether they can learn a specified technology.
  • If eligible and the technology is part of their expertise, it returns a positive message; otherwise, it indicates ineligibility or lack of learning capability.
  • An instance of Instructor is created with specific attributes, and the allocate_course method is called to assess course allocation for 'Data Science'.
python

Output

text

Next in this series: Python Encapsulation & Static Keyword: OOP Design Guide →

Frequently Asked Questions

Calling L.upper on a list raises an AttributeError because lists don't have an upper method; only string objects do.
To append a character to a string in Python, you should use the + operator, like s = s + 'x', to create a new string with the appended character.
The type function returns the data type of the object passed to it, confirming the type of the variable.
The blog emphasizes that in Python, every entity is treated as an object, which allows for encapsulation, inheritance, and polymorphism.

How was this tutorial?