A Python class is a blueprint or user-defined template used in Object-Oriented Programming (OOP) to define the attributes (data) and methods (functions) that objects created from the class will possess.

  • Definition: Classes are created using the class keyword followed by the class name (typically in PascalCase) and a colon.

  • Instantiation: To create an object (instance) from a class, you call the class like a function (e.g., my_object = MyClass()), which automatically triggers the constructor method __init__().

  • Attributes: Instance attributes are specific to each object and are defined using self inside __init__, while class attributes are shared across all instances.

  • Methods: These are functions defined within the class that allow objects to perform actions; the first argument is conventionally named self to refer to the current instance.

class Dog:
    # Class attribute (shared by all instances)
    species = "Canis familiaris"

    # Constructor (initializer)
    def __init__(self, name, age):
        self.name = name  # Instance attribute
        self.age = age    # Instance attribute

    # Instance method
    def speak(self, sound):
        return f"{self.name} says {sound}"

# Creating an object (instantiation)
my_dog = Dog("Buddy", 5)
print(my_dog.speak("Woof"))  # Output: Buddy says Woof

Python classes support advanced OOP features such as inheritance (creating new classes from existing ones), encapsulation (hiding internal data using naming conventions like _ or __), and special methods (dunder methods like __str__ and __len__) that allow objects to behave like built-in types.

Functions are very different from classes. It looks like you took a function and just changed the def to class. I guess that mostly works in your case, but it's not how classes are supposed to go.

Classes contain functions (methods) and data. For example, you have a ball:

class Ball(object):
    # __init__ is a special method called whenever you try to make
    # an instance of a class. As you heard, it initializes the object.
    # Here, we'll initialize some of the data.
    def __init__(self):
        # Let's add some data to the [instance of the] class.
        self.position = (100, 100)
        self.velocity = (0, 0)

    # We can also add our own functions. When our ball bounces,
    # its vertical velocity will be negated. (no gravity here!)
    def bounce(self):
        self.velocity = (self.velocity[0], -self.velocity[1])

Now we have a Ball class. How can we use it?

>>> ball1 = Ball()
>>> ball1
<Ball object at ...>

It doesn't look very useful. The data is where it could be useful:

>>> ball1.position
(100, 100)
>>> ball1.velocity
(0, 0)
>>> ball1.position = (200, 100)
>>> ball1.position
(200, 100)

Alright, cool, but what's the advantage over a global variable? If you have another Ball instance, it will remain independent:

>>> ball2 = Ball()
>>> ball2.velocity = (5, 10)
>>> ball2.position
(100, 100)
>>> ball2.velocity
(5, 10)

And ball1 remains independent:

>>> ball1.velocity
(0, 0)

Now what about that bounce method (function in a class) we defined?

>>> ball2.bounce()
>>> ball2.velocity
(5, -10)

The bounce method caused it to modify the velocity data of itself. Again, ball1 was not touched:

>>> ball1.velocity

Application

A ball is neat and all, but most people aren't simulating that. You're making a game. Let's think of what kinds of things we have:

  • A room is the most obvious thing we could have.

So let's make a room. Rooms have names, so we'll have some data to store that:

class Room(object):
    # Note that we're taking an argument besides self, here.
    def __init__(self, name):
        self.name = name  # Set the room's name to the name we got.

And let's make an instance of it:

>>> white_room = Room("White Room")
>>> white_room.name
'White Room'

Spiffy. This turns out not to be all that useful if you want different rooms to have different functionality, though, so let's make a subclass. A subclass inherits all functionality from its superclass, but you can add more functionality or override the superclass's functionality.

Let's think about what we want to do with rooms:

We want to interact with rooms.

And how do we do that?

The user types in a line of text that gets responded to.

How it's responded do depends on the room, so let's make the room handle that with a method called interact:

class WhiteRoom(Room):  # A white room is a kind of room.
    def __init__(self):
        # All white rooms have names of 'White Room'.
        self.name = 'White Room'

    def interact(self, line):
        if 'test' in line:
            print "'Test' to you, too!"

Now let's try interacting with it:

>>> white_room = WhiteRoom()  # WhiteRoom's __init__ doesn't take an argument (even though its superclass's __init__ does; we overrode the superclass's __init__)
>>> white_room.interact('test')
'Test' to you, too!

Your original example featured moving between rooms. Let's use a global variable called current_room to track which room we're in.1 Let's also make a red room.

1. There's better options besides global variables here, but I'm going to use one for simplicity.

class RedRoom(Room):  # A red room is also a kind of room.
    def __init__(self):
        self.name = 'Red Room'

    def interact(self, line):
        global current_room, white_room
        if 'white' in line:
            # We could create a new WhiteRoom, but then it
            # would lose its data (if it had any) after moving
            # out of it and into it again.
            current_room = white_room

Now let's try that:

>>> red_room = RedRoom()
>>> current_room = red_room
>>> current_room.name
'Red Room'
>>> current_room.interact('go to white room')
>>> current_room.name
'White Room'

Exercise for the reader: Add code to WhiteRoom's interact that allows you to go back to the red room.

Now that we have everything working, let's put it all together. With our new name data on all rooms, we can also show the current room in the prompt!

def play_game():
    global current_room
    while True:
        line = raw_input(current_room.name + '> ')
        current_room.interact(line)

You might also want to make a function to reset the game:

def reset_game():
    global current_room, white_room, red_room
    white_room = WhiteRoom()
    red_room = RedRoom()
    current_room = white_room

Put all of the class definitions and these functions into a file and you can play it at the prompt like this (assuming they're in mygame.py):

>>> import mygame
>>> mygame.reset_game()
>>> mygame.play_game()
White Room> test
'Test' to you, too!
White Room> go to red room
Red Room> go to white room
White Room>

To be able to play the game just by running the Python script, you can add this at the bottom:

def main():
    reset_game()
    play_game()

if __name__ == '__main__':  # If we're running as a script...
    main()

And that's a basic introduction to classes and how to apply it to your situation.

Answer from icktoofay on Stack Overflow
🌐
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

Python - Classes and OOP Basics - Stack Overflow
I do not fully understand classes. I have read the python documentation and several other tutorials. I get the basic gist of it but don't understand the nuance. For instance in my code here: c... 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
What is a class?
First: you need to know that "class" and "class instance" are completely separate things, even though people often use the word "class" or "object" when they mean a "class instance". A class is the instruction book on how to build a bucket. The class instance is that bucket that the computer builds for you based on the instructions in the class. The instructions are tailored so that the bucket is a perfect fit for a very specific set of data you want to store. So if you are coding a game, for example, you may want a bucket that holds holds the player's stats, health, inventory, etc. Sure you could store all of that data without a bucket, but keeping it all in one place makes the code very neat. Another very important note about classes: They only exist to make the programmer's life easier. They are not required to code and they won't make the code run faster or better. They only exist as an organizational tool for the programmer. More on reddit.com
🌐 r/learnpython
43
17
December 20, 2023
When and why should I use Class?
Classes are for when you want to bundle the data of some thing and functions to operate on that data together. More on reddit.com
🌐 r/learnpython
41
61
October 31, 2023
🌐
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.
🌐
Pluralsight
pluralsight.com › tech insights & how-to guides › software development
A guide to class types in Python | Pluralsight
We’d want some sort of blueprint that specifies what a book data type should be, and makes sure none of those things can happen. That’s where creating our own classes comes in. Just like Python gives us str, int, and list, we can create our own Book, Patron, and Library types.
🌐
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.
Top answer
1 of 6
71

Functions are very different from classes. It looks like you took a function and just changed the def to class. I guess that mostly works in your case, but it's not how classes are supposed to go.

Classes contain functions (methods) and data. For example, you have a ball:

class Ball(object):
    # __init__ is a special method called whenever you try to make
    # an instance of a class. As you heard, it initializes the object.
    # Here, we'll initialize some of the data.
    def __init__(self):
        # Let's add some data to the [instance of the] class.
        self.position = (100, 100)
        self.velocity = (0, 0)

    # We can also add our own functions. When our ball bounces,
    # its vertical velocity will be negated. (no gravity here!)
    def bounce(self):
        self.velocity = (self.velocity[0], -self.velocity[1])

Now we have a Ball class. How can we use it?

>>> ball1 = Ball()
>>> ball1
<Ball object at ...>

It doesn't look very useful. The data is where it could be useful:

>>> ball1.position
(100, 100)
>>> ball1.velocity
(0, 0)
>>> ball1.position = (200, 100)
>>> ball1.position
(200, 100)

Alright, cool, but what's the advantage over a global variable? If you have another Ball instance, it will remain independent:

>>> ball2 = Ball()
>>> ball2.velocity = (5, 10)
>>> ball2.position
(100, 100)
>>> ball2.velocity
(5, 10)

And ball1 remains independent:

>>> ball1.velocity
(0, 0)

Now what about that bounce method (function in a class) we defined?

>>> ball2.bounce()
>>> ball2.velocity
(5, -10)

The bounce method caused it to modify the velocity data of itself. Again, ball1 was not touched:

>>> ball1.velocity

Application

A ball is neat and all, but most people aren't simulating that. You're making a game. Let's think of what kinds of things we have:

  • A room is the most obvious thing we could have.

So let's make a room. Rooms have names, so we'll have some data to store that:

class Room(object):
    # Note that we're taking an argument besides self, here.
    def __init__(self, name):
        self.name = name  # Set the room's name to the name we got.

And let's make an instance of it:

>>> white_room = Room("White Room")
>>> white_room.name
'White Room'

Spiffy. This turns out not to be all that useful if you want different rooms to have different functionality, though, so let's make a subclass. A subclass inherits all functionality from its superclass, but you can add more functionality or override the superclass's functionality.

Let's think about what we want to do with rooms:

We want to interact with rooms.

And how do we do that?

The user types in a line of text that gets responded to.

How it's responded do depends on the room, so let's make the room handle that with a method called interact:

class WhiteRoom(Room):  # A white room is a kind of room.
    def __init__(self):
        # All white rooms have names of 'White Room'.
        self.name = 'White Room'

    def interact(self, line):
        if 'test' in line:
            print "'Test' to you, too!"

Now let's try interacting with it:

>>> white_room = WhiteRoom()  # WhiteRoom's __init__ doesn't take an argument (even though its superclass's __init__ does; we overrode the superclass's __init__)
>>> white_room.interact('test')
'Test' to you, too!

Your original example featured moving between rooms. Let's use a global variable called current_room to track which room we're in.1 Let's also make a red room.

1. There's better options besides global variables here, but I'm going to use one for simplicity.

class RedRoom(Room):  # A red room is also a kind of room.
    def __init__(self):
        self.name = 'Red Room'

    def interact(self, line):
        global current_room, white_room
        if 'white' in line:
            # We could create a new WhiteRoom, but then it
            # would lose its data (if it had any) after moving
            # out of it and into it again.
            current_room = white_room

Now let's try that:

>>> red_room = RedRoom()
>>> current_room = red_room
>>> current_room.name
'Red Room'
>>> current_room.interact('go to white room')
>>> current_room.name
'White Room'

Exercise for the reader: Add code to WhiteRoom's interact that allows you to go back to the red room.

Now that we have everything working, let's put it all together. With our new name data on all rooms, we can also show the current room in the prompt!

def play_game():
    global current_room
    while True:
        line = raw_input(current_room.name + '> ')
        current_room.interact(line)

You might also want to make a function to reset the game:

def reset_game():
    global current_room, white_room, red_room
    white_room = WhiteRoom()
    red_room = RedRoom()
    current_room = white_room

Put all of the class definitions and these functions into a file and you can play it at the prompt like this (assuming they're in mygame.py):

>>> import mygame
>>> mygame.reset_game()
>>> mygame.play_game()
White Room> test
'Test' to you, too!
White Room> go to red room
Red Room> go to white room
White Room>

To be able to play the game just by running the Python script, you can add this at the bottom:

def main():
    reset_game()
    play_game()

if __name__ == '__main__':  # If we're running as a script...
    main()

And that's a basic introduction to classes and how to apply it to your situation.

2 of 6
7

I'm sure you've heard all this before, but I'll give it a go.

Classes are a way to group up a bunch of function and variables into a single object. When you get all the way down to it, this is simply a way of organizing everything into groups that make sense. There are benefits down the road for making things easier to understand, debug, extend, or maintain, but basically its just a way to make something more defined in your mental model.

Your code looks like you are trying to write your entire program inside an 'object' (really, you just have an incorrectly written function).

Consider this instead.

Think of your mental model of rooms which have doors to them and whiteboards in them. Doors have a color. Also, whiteboards can have some text written on them. We'll leave it there to be simple.

To me, this suggests 3 different objects -- a door object that has a string for color, a whiteboard object that has a string for the text, and a room object that has a door and a whiteboard.

Consider the following code:

class Door(object):
    def __init__(self, color):
        self.color = color

class Whiteboard(object):
    def __init__(self, default_text=''):
        self.text = ''
        self.write_text(default_text)

    def write_text(self, text):
        self.text += text

    def erase(self):
        self.text = ''


class Room(object):
    def __init__(self, doorcolor, whiteboardtext=''):
        self.whiteboard = Whiteboard(whiteboardtext)
        self.door = Door(doorcolor)




# make a room with a red door and no text on the whiteboard
room1 = Room('red')

# make a room with a blue door and 'yeah, whiteboard' on the whiteboard
room2 = Room('blue', 'yeah, whiteboard')

# make a room with a green door
room3 = Room('green')



# now I can play around with my 'rooms' and they keep track of everything internally

print 'room 1 door color: ' + room1.door.color
print 'room 2 door color: ' + room2.door.color


# all my rooms have a door and a whiteboard, but each one is different and self contained. For example
# if I write on room 1's whiteboard, it doesn't change anything about room 3s

print 'room1 whiteboard: ' + room1.whiteboard.text
print 'room2 whiteboard: ' + room2.whiteboard.text
print 'room3 whiteboard: ' + room3.whiteboard.text

print '-- changeing room 1 whiteboard text --'

room1.whiteboard.write_text('oop is really helpful')


print 'room1 whiteboard: ' + room1.whiteboard.text
print 'room2 whiteboard: ' + room2.whiteboard.text
print 'room3 whiteboard: ' + room3.whiteboard.text

The init function is what gets called when you 'initialize' a new instance of your class. In the example I am making 3 Room objects which each create a Door and Whiteboard object internally. The parameters I pass into the constructor Room(parameter1, parameter2) get passed to the init functions - you can see I'm using this to set the door color and optionally some text on the whiteboard. Also notice that the variables that 'belong' to the objects are referenced with self - this reference is what gets passed in as the first parameter to all class functions (and becomes more important later when you are extending classes and other more advanced things).

Find elsewhere
🌐
Code Institute
codeinstitute.net › blog › python classes
Python Classes: What are They and When to Use - Code Institute Global
June 2, 2022 - Python employs objects to accomplish data operations. Python classes are responsible for the creation of such valuable items.
🌐
Tutorialspoint
tutorialspoint.com › python › python_classes_objects.htm
Python - Classes and Objects
For instance, numbers, strings, lists, dictionaries, and other similar entities of a program are objects of the corresponding built-in class. In Python, a class named Object is the base or parent class for all the classes, built-in as well as user defined.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-classes-and-objects
Python Classes and Objects - GeeksforGeeks
dog1.name accesses the object’s instance attribute and dog1.species accesses the shared class attribute. __str__ method allows us to define a custom string representation of an object. By default, when we print an object or convert it to a string using str(), Python uses the default implementation, which returns a string like <__main__.ClassName object at 0x00000123>.
Published   4 hours ago
🌐
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.
🌐
IBM
ibm.com › docs › en › spss-modeler › 18.6.0
Defining a Class
We cannot provide a description for this page right now
🌐
BelieveMy
believemy.com › en › glossaries › python › class
The complete guide to Python classes | Python glossary
A class is used in Python to create a model that can be used to create objects: this is known as object-oriented programming.
🌐
Sololearn
sololearn.com › en › Discuss › 2868849 › what-does-class-mean-in-python
What does @class mean in python? | Sololearn: Learn to code for FREE!
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. An object is created using the constructor of the class.
🌐
Python Geeks
pythongeeks.org › python geeks › learn python › classes in python with examples
Classes in Python with Examples - Python Geeks
July 30, 2021 - In Python, we use classes to create objects. A class is a tool, like a blueprint or a template, for creating objects. It allows us to bundle data and functionality together. Since everything is an object, to create anything, in Python, we need ...
🌐
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.
🌐
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.
🌐
DigitalOcean
digitalocean.com › community › tutorials › python-classes-objects
Python Classes and Objects | DigitalOcean
August 4, 2022 - If you remember, basic data types in python refer to only one kind of data at a time. How would it be if you could declare a data type which itself contains more than one data types and can work with them with the help of any function? Python class gives you that opportunity.
🌐
Medium
medium.com › the-modern-scientist › python-classes-made-easy-a-beginners-guide-c9634ddca518
Python Classes Made Easy: A Beginner’s Guide | by Prince Samuel | The Modern Scientist | Medium
February 27, 2023 - Classes are a fundamental concept in object-oriented programming, and they allow programmers to create their own data types with their own attributes and methods. In Python, we define classes using the class keyword, and we can create objects ...
🌐
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.
🌐
PYnative
pynative.com › home › python › python object-oriented programming (oop) › python class method explained with examples
Python Class Method Explained With Examples – PYnative
August 28, 2021 - Apart from a decorator, the built-in function classmethod() is used to convert a normal method into a class method. The classmethod() is an inbuilt function in Python, which returns a class method for a given function.