๐ŸŒ
Python documentation
docs.python.org โ€บ 3 โ€บ tutorial โ€บ classes.html
9. Classes โ€” Python 3.14.3 documentation
It is a mixture of the class mechanisms found in C++ and Modula-3. Python classes provide all the standard features of Object Oriented Programming: the class inheritance mechanism allows multiple base classes, a derived class can override any ...
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ python_classes.asp
Python Classes
Almost everything in Python is an object, with its properties and methods. A Class is like an object constructor, or a "blueprint" for creating objects.
Discussions

Im new to python. Classes and objects
Yes. You have the basic idea. Here's my guide to flesh that out a bit more ... Classes for Beginners v2.1 May 2023 A lot of beginners struggle to get their heads around classes, but they are pretty much fundamental to object orientated programming (OOPs). They can be thought of as the programming equal of moulds used in factories as templates (or blueprints) for making lots of things that are identical. Imagine pouring molten iron into a mould to make a simple iron pot. You might produce a set of instructions to be included with the pots that tell an owner how to cook using the pot, how to care for it, etc. The same instructions apply to every pot, but what owners actually do is entirely up to them. Some might make soup, another person a stew, etc. Python classes A class defines the basics of a possible Python object and some methods that come with it Methods are like functions, but apply to objects, known as instances, made using a class When we create a Python object using a class, we call it "creating an instance of a class" - an instance is just another Python object If you have a class called Room, you would create instances like this: lounge = Room() kitchen = Room() hall = Room() As you would typically want to store the main dimensions (height, length, width) of a room, whatever it is used for, it makes sense to define that when the instance is created. You would therefore have a method called __init__ that accepts height, length, width and when you create an instance of Room you would provide that information: lounge = Room(1300, 4000, 2000) The __init__ method is called automatically when you create an instance. It is short for initialise (intialize). It is possible to specify default values in an __init__ method, but this doesn't make a lot of sense for the size of a room. Accessing attributes of a class instance You can reference the information using lounge.height, lounge.width, and so on. These are attributes of the lounge instance. We are assuming the measurements are in mm. A method can be included in the class that converts between mm and ft. Thus, for example, we can then write lounge.height_in_ft(). printing an attribute You can output the value of any attribute by just using the name of the instance followed by a dot and the attribute name. For example, print(lounge.height) property decorator A useful decorator is @property, which allows you to refer to a method as if it is an attribute. This would allow you to say lounge.height_in_ft instead of lounge.height_in_ft(). In the example code shown later, @property is used for width_in_ft but not height_in_ft. The use of self to refer to an instance Methods in classes are usually defined with a first parameter of self: def __init__(self, height, length, width): # code for __init__ def height_in_ft(self): # code to return height The self is a shorthand way of referring to an instance. The automatic passing of the reference to the instance (assigned to self) is a key difference between a function call and a method call. When you use lounge.height_in_ft() the method knows that any reference to self means the lounge instance, so self.height means lounge.height but you don't have to write the code for each individual instance. Thus, kitchen.height_in_ft() and bathroom.height_in_ft() use the same method, but you don't have to pass the height of the instance as the method can reference it using self.height human-readable representation of an instance If you want to output all the information about an instance, that would get laborious. There's a method you can add called __str__ which returns a string representation of an instance. This is used automatically by functions like str and print. The example code below includes both the laborious way and using the above method. magic methods The standard methods you can add that start and end with a double underscore, like __init__, __str__, and many more, are often called magic methods or dunder methods where dunder is short for double underscore. EXAMPLE Room class The code shown at the end of this post/comment will generate the following output: Lounge height: 1300 length: 4000 width: 2000 Snug: height: 1300, length: 2500 width: 2000 Lounge length in feet: 4.27 Snug wall area: 11700000.00 in sq.mm., 125.94 in sq.ft. Snug width in feet: 6.56 Note that a method definition that is preceded by the command, @staticmethod (a decorator) is really just a function that does not include the self reference to the calling instance. It is included in a class definition for convenience and can be called by reference to the class or the instance: Room.mm_to_ft(mm) lounge.mm_to_ft(mm) Here's the code for the full programme: class Room(): def __init__(self, name, height, length, width): self.name = name self.height = height self.length = length self.width = width @staticmethod def mm_to_ft(mm): return mm * 0.0032808399 @staticmethod def sqmm_to_sqft(sqmm): return sqmm * 1.07639e-5 def height_in_ft(self): return Room.mm_to_ft(self.height) @property def width_in_ft(self): return Room.mm_to_ft(self.width) def length_in_ft(self): return Room.mm_to_ft(self.length) def wall_area(self): return self.length * 2 * self.height + self.width * 2 * self.height def __str__(self): return (f"{self.name}: " f"height: {self.height}, " f"length: {self.length} " f"width: {self.width}" ) lounge = Room('Lounge', 1300, 4000, 2000) snug = Room('Snug', 1300, 2500, 2000) print(lounge.name, "height:", lounge.height, "length:", lounge.length, "width:", lounge.width) print(snug) # uses __str__ method # f-strings are used for formatting, the :.2f part formats decimal numbers rounded to 2 places print(f"{lounge.name} length in feet: {lounge.height_in_ft():.2f}") # note, () to call method print(f"{snug.name} wall area: {snug.wall_area():.2f} in sq.mm., " f"{snug.sqmm_to_sqft(snug.wall_area()):.2f} in sq.ft." ) print(f"Snug width in feet: {snug.width_in_ft:.2f}") # note, no () after method More on reddit.com
๐ŸŒ r/learnpython
14
12
July 12, 2023
Class coding and usage
Iโ€™m trying to extend my Python skills and feel that I need to tackle the subject of Classes. Iโ€™ve read a few tutorials, but none of them seem to deal with the topic in a way that I can fully relate to. By pure coincidence this post popped up which seemed to me to be a project to which I ... More on discuss.python.org
๐ŸŒ discuss.python.org
0
1
April 9, 2023
oop - When should I be using classes in Python? - Stack Overflow
I have been programming in python for about two years; mostly data stuff (pandas, mpl, numpy), but also automation scripts and small web apps. I'm trying to become a better programmer and increase... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Classes. Please explain like Iโ€™m 5.
When programming you often need to keep track of multiple data about a real world object and provide some ways of changing that data in specific ways. Let's take a common first example: say you're building a program that'll run on an ATM. Then you will need to look up accounts which could have associated data like the type of account (checking vs savings, etc), the balance, the date it was opened, the owner, etc. And you'll want to be able to do certain things to the account like retrieve its balance, make a withdrawal, close it, etc. So you could build a class for accounts that looks something like this. # I'm going to need a datetime object later on import datetime # header syntax class Account: # __init__ is the method (a function inside a class is called a method) # where we set up the data we want to keep track of for a new object. # Notice that all methods have a first parameter called self. Don't # worry why just yet, just don't forget to add it. def __init__(self, acc_type, initial_balance, owner, date_opened=None): self.type = acc_type self.balance = initial_balance self.date_opened = date_opened or datetime.datetime.today() self.owner = owner # We'll also want to be able to withdraw funds. But ONLY if there is # enough in the account to be able to withdraw the requested amount. def withdraw(self, amount): if self.balance >= amount: self.balance -= amount else: # Assume that I've defined this error somewhere previously. raise InsufficientBalanceError As you can see, a class is just a way to keep track of all of the data about a particular real-world (usually) object as well as any functions that we want on use with that data. And now that we've defined this new data type/ class, we can create objects like this. jims_account = Account('checking', 12, 'James Darkmagic') omins_account = Account('savings', 2000, 'Omin Dran') And then if Omin wanted to make a withdrawal, we'd use dot notation to call the withdraw method. print(omins_account.balance) # 2000 omins_account.withdraw(500) print(omins_account.balance) # 1500 If we tried the same on Jim's account (jims_account.withdraw(500)), we'd get an InsufficientBalanceError because he only has 12 gp in his account. One thing to note is that classes are not necessary to write any program, but they make organization easier and help the programmer keep a better mental model of the data types that are in play. Now here's a question to see if you've understood. Can you think of some other class that might be useful to create for an ATM/ banking program? What types of data and methods (functions) would you collect together into the class? More on reddit.com
๐ŸŒ r/learnpython
71
226
February 23, 2021
People also ask

How do I learn Python?

To learn Python, begin by choosing a structured course or specialization that matches your skill level. Dedicate time to practice coding regularly, as hands-on experience is crucial. Utilize online resources, such as forums and coding communities, to seek help and collaborate with others. Finally, work on personal projects to apply what you've learned and reinforce your skills.

๐ŸŒ
coursera.org
coursera.org โ€บ courses
Best Python Courses & Certificates [2026] | Coursera
What are the best Python courses online?

There are many excellent online Python courses available. For beginners, the BiteSize Python for Absolute Beginners Specialization offers a gentle introduction. For those looking to advance their skills, the AI and Machine Learning Essentials with Python Specialization provides a solid foundation in applying Python to AI. Additionally, the Data Analysis with Python Specialization is great for those interested in data science.

๐ŸŒ
coursera.org
coursera.org โ€บ courses
Best Python Courses & Certificates [2026] | Coursera
Can I study Python for free on Coursera?

Yes. You can start learning python on Coursera for free in two ways:

  1. Preview the first module of many python courses at no cost. This includes video lessons, readings, graded assignments, and Coursera Coach (where available).
  2. Start a 7-day free trial for Specializations or Coursera Plus. This gives you full access to all course content across eligible programs within the timeframe of your trial.

If you want to keep learning, earn a certificate in python, or unlock full course access after the preview or trial, you can upgrade or apply for financial aid.

๐ŸŒ
coursera.org
coursera.org โ€บ courses
Best Python Courses & Certificates [2026] | Coursera
๐ŸŒ
Google
developers.google.com โ€บ google for education โ€บ python
Google's Python Class | Python Education | Google for Developers
Welcome to Google's Python Class -- this is a free class for people with a little bit of programming experience who want to learn Python. The class includes written materials, lecture videos, and lots of code exercises to practice Python coding.
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ gloss_python_class.asp
Python Class
Almost everything in Python is an object, with its properties and methods. A Class is like an object constructor, or a "blueprint" for creating objects.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-classes-and-objects
Python Classes and Objects - GeeksforGeeks
A class in Python is a user-defined template for creating objects. It bundles data and functions together, making it easier to manage and use them. When we create a new class, we define a new type of object.
Published ย  1 week ago
๐ŸŒ
Medium
medium.com โ€บ @reetesh043 โ€บ the-ultimate-guide-to-python-classes-and-objects-8ecac5a1a055
The Ultimate Guide to Python Classes and Objects | by Reetesh Kumar | Medium
June 16, 2025 - Classes are the fundamental building blocks of Object-Oriented Programming (OOP) in Python. A class defines a type or blueprint for objects, specifying what attributes (data) and methods (functions) those objects will have.
Find elsewhere
๐ŸŒ
Coursera
coursera.org โ€บ courses
Best Python Courses & Certificates [2026] | Coursera
Python courses can help you learn programming fundamentals, data analysis, web development, and automation techniques. You can build skills in writing clean code, debugging, and using libraries like Pandas and NumPy for data manipulation.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ im new to python. classes and objects
r/learnpython on Reddit: Im new to python. Classes and objects
July 12, 2023 -

From what I understand....

Class - is basically the blueprint from which you create objects. This is where you state what attributes the item will have (e.g. name, colour) but you wont actually assign the value of the attribute (e.g. iphone, red).

Object - is basically the values (e.g. the actual name/colour of the item) to the attributes/properties you chose the item to have

Is that right? If possible, if you have anything to add. I would really appreciate if you explain to me in an easy to understand way. Im new to python and computers as a whole but slowly learning

Thankyou in advance

Top answer
1 of 5
12
Yes. You have the basic idea. Here's my guide to flesh that out a bit more ... Classes for Beginners v2.1 May 2023 A lot of beginners struggle to get their heads around classes, but they are pretty much fundamental to object orientated programming (OOPs). They can be thought of as the programming equal of moulds used in factories as templates (or blueprints) for making lots of things that are identical. Imagine pouring molten iron into a mould to make a simple iron pot. You might produce a set of instructions to be included with the pots that tell an owner how to cook using the pot, how to care for it, etc. The same instructions apply to every pot, but what owners actually do is entirely up to them. Some might make soup, another person a stew, etc. Python classes A class defines the basics of a possible Python object and some methods that come with it Methods are like functions, but apply to objects, known as instances, made using a class When we create a Python object using a class, we call it "creating an instance of a class" - an instance is just another Python object If you have a class called Room, you would create instances like this: lounge = Room() kitchen = Room() hall = Room() As you would typically want to store the main dimensions (height, length, width) of a room, whatever it is used for, it makes sense to define that when the instance is created. You would therefore have a method called __init__ that accepts height, length, width and when you create an instance of Room you would provide that information: lounge = Room(1300, 4000, 2000) The __init__ method is called automatically when you create an instance. It is short for initialise (intialize). It is possible to specify default values in an __init__ method, but this doesn't make a lot of sense for the size of a room. Accessing attributes of a class instance You can reference the information using lounge.height, lounge.width, and so on. These are attributes of the lounge instance. We are assuming the measurements are in mm. A method can be included in the class that converts between mm and ft. Thus, for example, we can then write lounge.height_in_ft(). printing an attribute You can output the value of any attribute by just using the name of the instance followed by a dot and the attribute name. For example, print(lounge.height) property decorator A useful decorator is @property, which allows you to refer to a method as if it is an attribute. This would allow you to say lounge.height_in_ft instead of lounge.height_in_ft(). In the example code shown later, @property is used for width_in_ft but not height_in_ft. The use of self to refer to an instance Methods in classes are usually defined with a first parameter of self: def __init__(self, height, length, width): # code for __init__ def height_in_ft(self): # code to return height The self is a shorthand way of referring to an instance. The automatic passing of the reference to the instance (assigned to self) is a key difference between a function call and a method call. When you use lounge.height_in_ft() the method knows that any reference to self means the lounge instance, so self.height means lounge.height but you don't have to write the code for each individual instance. Thus, kitchen.height_in_ft() and bathroom.height_in_ft() use the same method, but you don't have to pass the height of the instance as the method can reference it using self.height human-readable representation of an instance If you want to output all the information about an instance, that would get laborious. There's a method you can add called __str__ which returns a string representation of an instance. This is used automatically by functions like str and print. The example code below includes both the laborious way and using the above method. magic methods The standard methods you can add that start and end with a double underscore, like __init__, __str__, and many more, are often called magic methods or dunder methods where dunder is short for double underscore. EXAMPLE Room class The code shown at the end of this post/comment will generate the following output: Lounge height: 1300 length: 4000 width: 2000 Snug: height: 1300, length: 2500 width: 2000 Lounge length in feet: 4.27 Snug wall area: 11700000.00 in sq.mm., 125.94 in sq.ft. Snug width in feet: 6.56 Note that a method definition that is preceded by the command, @staticmethod (a decorator) is really just a function that does not include the self reference to the calling instance. It is included in a class definition for convenience and can be called by reference to the class or the instance: Room.mm_to_ft(mm) lounge.mm_to_ft(mm) Here's the code for the full programme: class Room(): def __init__(self, name, height, length, width): self.name = name self.height = height self.length = length self.width = width @staticmethod def mm_to_ft(mm): return mm * 0.0032808399 @staticmethod def sqmm_to_sqft(sqmm): return sqmm * 1.07639e-5 def height_in_ft(self): return Room.mm_to_ft(self.height) @property def width_in_ft(self): return Room.mm_to_ft(self.width) def length_in_ft(self): return Room.mm_to_ft(self.length) def wall_area(self): return self.length * 2 * self.height + self.width * 2 * self.height def __str__(self): return (f"{self.name}: " f"height: {self.height}, " f"length: {self.length} " f"width: {self.width}" ) lounge = Room('Lounge', 1300, 4000, 2000) snug = Room('Snug', 1300, 2500, 2000) print(lounge.name, "height:", lounge.height, "length:", lounge.length, "width:", lounge.width) print(snug) # uses __str__ method # f-strings are used for formatting, the :.2f part formats decimal numbers rounded to 2 places print(f"{lounge.name} length in feet: {lounge.height_in_ft():.2f}") # note, () to call method print(f"{snug.name} wall area: {snug.wall_area():.2f} in sq.mm., " f"{snug.sqmm_to_sqft(snug.wall_area()):.2f} in sq.ft." ) print(f"Snug width in feet: {snug.width_in_ft:.2f}") # note, no () after method
2 of 5
7
The blueprint analogy is not bad but it's just an analogy, it does not hold to reality. The better description is that a class is a type. And like all types in python it has attributes and methods. You know that floating point numbers in python are usually refer as a type. That type is float. It is actually a class and every time you create a float variable you are creating an object of the class float. x = 3.1415 is the same as x = float(3.1415) Which looks more like an object created from a class and a value. And yes there are all kinds of attributes and methods defined in the float class. For example the float class has a method as_integer_ratio() which will return a numerator and a denominator representing the value of the float as a fraction. print(x.as_integer_ratio()) output (7074029114692207, 2251799813685248)
๐ŸŒ
Python.org
discuss.python.org โ€บ python help
Class coding and usage - Python Help - Discussions on Python.org
April 9, 2023 - Iโ€™m trying to extend my Python skills and feel that I need to tackle the subject of Classes. Iโ€™ve read a few tutorials, but none of them seem to deal with the topic in a way that I can fully relate to. By pure coincidence this post popped up which seemed to me to be a project to which I ...
๐ŸŒ
Lancaster University
lancaster.ac.uk โ€บ staff โ€บ drummonn โ€บ PHYS281 โ€บ demo-classes
Python classes - PHYS281
Almost everything in Python is an object. All objects (e.g., variables, functions) have a type. An object's type is also known as its class.
๐ŸŒ
Codecademy
codecademy.com โ€บ learn โ€บ cspath-python-objects โ€บ modules โ€บ cspath-python-classes โ€บ cheatsheet
Python Objects: Python: Classes Cheatsheet | Codecademy
A class can be defined using the class keyword. ... In Python, the built-in dir() function, without any argument, returns a list of all the attributes in the current scope.
๐ŸŒ
Harvard University
pll.harvard.edu โ€บ course โ€บ cs50s-introduction-artificial-intelligence-python
CS50's Introduction to Artificial Intelligence with Python | Harvard University
February 14, 2020 - CS50โ€™s Introduction to Artificial Intelligence with Python explores the concepts and algorithms at the foundation of modern artificial intelligence, diving into the ideas that give rise to technologies like game-playing engines, handwriting recognition, and machine translation. Through hands-on projects, students gain exposure to the theory behind graph search algorithms, classification, optimization, reinforcement learning, and other topics in artificial intelligence and machine learning as they incorporate them into their own Python programs.
๐ŸŒ
Mimo
mimo.org โ€บ glossary โ€บ python โ€บ class
Python Class: Syntax and Examples [Python Tutorial]
A class in Python is a blueprint for creating objects. An object is an instance of a class, with its own unique attributes and methods. You define a class using the class keyword and initialize its attributes with the special __init__() method.
๐ŸŒ
Harvard University
pll.harvard.edu โ€บ course โ€บ cs50s-introduction-programming-python
CS50's Introduction to Programming with Python | Harvard University
November 8, 2021 - An introduction to programming using a language called Python. Learn how to read and write code as well as how to test and "debug" it. Designed for students with and without prior programming experience who'd like to learn Python specifically.
๐ŸŒ
Real Python
realpython.com โ€บ python-classes
Python Classes: The Power of Object-Oriented Programming โ€“ Real Python
December 15, 2024 - A class in Python serves as a blueprint for creating objects, which are instances of the class. You use classes when you need to encapsulate related data and functions, making your code modular and easier to manage.
๐ŸŒ
Medium
medium.com โ€บ hackernoon โ€บ improve-your-python-python-classes-and-object-oriented-programming-d09ff461168d
Improve Your Python: Python Classes and Object Oriented Programming | by Jeff Knupp | HackerNoon.com | Medium
May 22, 2019 - The class is a fundamental building block in Python. It is the underpinning for not only many popular programs and libraries, but the Python standard library as well. Understanding what classes are, when to use them, and how they can be useful is essential, and the goal of this article.
๐ŸŒ
Devcamp
bottega.devcamp.com โ€บ full-stack-development-javascript-python โ€บ guide โ€บ how-to-get-set-data-python-class
How to Get and Set Data in a Python Class
But because everything is an object in Python that's what makes it possible for us to query and to set values anytime we want. And so we don't have to create special functions to do it because if I come down here and I'm going to get rid of the formatter but if I come down here and I want to get access to the client value I can just type print and then Google.client and because this is an object because when we create this invoice class or when we instantiate it.
๐ŸŒ
HackerEarth
hackerearth.com โ€บ practice โ€บ python โ€บ object oriented programming โ€บ classes and objects i
Classes and Objects I Tutorials & Notes | Python | HackerEarth
A class is a code template for creating objects. Objects have member variables and have behaviour associated with them. In python a class is created by the keyword class.
Top answer
1 of 6
308

Classes are the pillar of Object Oriented Programming. OOP is highly concerned with code organization, reusability, and encapsulation.

First, a disclaimer: OOP is partially in contrast to Functional Programming, which is a different paradigm used a lot in Python. Not everyone who programs in Python (or surely most languages) uses OOP. You can do a lot in Java 8 that isn't very Object Oriented. If you don't want to use OOP, then don't. If you're just writing one-off scripts to process data that you'll never use again, then keep writing the way you are.

However, there are a lot of reasons to use OOP.

Some reasons:

  • Organization: OOP defines well known and standard ways of describing and defining both data and procedure in code. Both data and procedure can be stored at varying levels of definition (in different classes), and there are standard ways about talking about these definitions. That is, if you use OOP in a standard way, it will help your later self and others understand, edit, and use your code. Also, instead of using a complex, arbitrary data storage mechanism (dicts of dicts or lists or dicts or lists of dicts of sets, or whatever), you can name pieces of data structures and conveniently refer to them.

  • State: OOP helps you define and keep track of state. For instance, in a classic example, if you're creating a program that processes students (for instance, a grade program), you can keep all the info you need about them in one spot (name, age, gender, grade level, courses, grades, teachers, peers, diet, special needs, etc.), and this data is persisted as long as the object is alive, and is easily accessible. In contrast, in pure functional programming, state is never mutated in place.

  • Encapsulation: With encapsulation, procedure and data are stored together. Methods (an OOP term for functions) are defined right alongside the data that they operate on and produce. In a language like Java that allows for access control, or in Python, depending upon how you describe your public API, this means that methods and data can be hidden from the user. What this means is that if you need or want to change code, you can do whatever you want to the implementation of the code, but keep the public APIs the same.

  • Inheritance: Inheritance allows you to define data and procedure in one place (in one class), and then override or extend that functionality later. For instance, in Python, I often see people creating subclasses of the dict class in order to add additional functionality. A common change is overriding the method that throws an exception when a key is requested from a dictionary that doesn't exist to give a default value based on an unknown key. This allows you to extend your own code now or later, allow others to extend your code, and allows you to extend other people's code.

  • Reusability: All of these reasons and others allow for greater reusability of code. Object oriented code allows you to write solid (tested) code once, and then reuse over and over. If you need to tweak something for your specific use case, you can inherit from an existing class and overwrite the existing behavior. If you need to change something, you can change it all while maintaining the existing public method signatures, and no one is the wiser (hopefully).

Again, there are several reasons not to use OOP, and you don't need to. But luckily with a language like Python, you can use just a little bit or a lot, it's up to you.

An example of the student use case (no guarantee on code quality, just an example):

Object Oriented

class Student(object):
    def __init__(self, name, age, gender, level, grades=None):
        self.name = name
        self.age = age
        self.gender = gender
        self.level = level
        self.grades = grades or {}

    def setGrade(self, course, grade):
        self.grades[course] = grade

    def getGrade(self, course):
        return self.grades[course]

    def getGPA(self):
        return sum(self.grades.values())/len(self.grades)

# Define some students
john = Student("John", 12, "male", 6, {"math":3.3})
jane = Student("Jane", 12, "female", 6, {"math":3.5})

# Now we can get to the grades easily
print(john.getGPA())
print(jane.getGPA())

Standard Dict

def calculateGPA(gradeDict):
    return sum(gradeDict.values())/len(gradeDict)

students = {}
# We can set the keys to variables so we might minimize typos
name, age, gender, level, grades = "name", "age", "gender", "level", "grades"
john, jane = "john", "jane"
math = "math"
students[john] = {}
students[john][age] = 12
students[john][gender] = "male"
students[john][level] = 6
students[john][grades] = {math:3.3}

students[jane] = {}
students[jane][age] = 12
students[jane][gender] = "female"
students[jane][level] = 6
students[jane][grades] = {math:3.5}

# At this point, we need to remember who the students are and where the grades are stored. Not a huge deal, but avoided by OOP.
print(calculateGPA(students[john][grades]))
print(calculateGPA(students[jane][grades]))
2 of 6
37

Whenever you need to maintain a state of your functions and it cannot be accomplished with generators (functions which yield rather than return). Generators maintain their own state.

If you want to override any of the standard operators, you need a class.

Whenever you have a use for a Visitor pattern, you'll need classes. Every other design pattern can be accomplished more effectively and cleanly with generators, context managers (which are also better implemented as generators than as classes) and POD types (dictionaries, lists and tuples, etc.).

If you want to write "pythonic" code, you should prefer context managers and generators over classes. It will be cleaner.

If you want to extend functionality, you will almost always be able to accomplish it with containment rather than inheritance.

As every rule, this has an exception. If you want to encapsulate functionality quickly (ie, write test code rather than library-level reusable code), you can encapsulate the state in a class. It will be simple and won't need to be reusable.

If you need a C++ style destructor (RAII), you definitely do NOT want to use classes. You want context managers.

๐ŸŒ
Code Institute
codeinstitute.net โ€บ blog โ€บ python classes
Python Classes: What are They and When to Use - Code Institute NL
June 2, 2022 - Python employs objects to accomplish data operations. Python classes are responsible for the creation of such valuable items.