Before looking at creating your own classes, it’s worth taking some time to understand the classes that already exist. I’m going to use the built-in integer class as an example here. What can you do with integers? You can create them and print them out: x = int("1A2B3", 16) print(x) # displays: 10… Answer from Rosuav on discuss.python.org
🌐
W3Schools
w3schools.com › python › python_classes.asp
Python Classes/Objects
Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Bootcamp Python Certificate Python Training ... Python is an object oriented programming language. 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.
🌐
Mimo
mimo.org › glossary › python › class
Python Class: Syntax and Examples [Python Tutorial]
Inheritance Promotes Reusability: Classes can inherit from other classes to reuse code and create a logical hierarchy. A "child" class gets all the functionality of a "parent" class. ... Become a Python developer.
Discussions

Class coding and usage
By pure coincidence this post popped up which seemed to me to be a project to which I could apply a ‘Class’. Rather than hijack that thread, I thought it better to create this RFC thread. This is a working example of what I’ve coded: import csv class movie: def __init__(self, title, direc... More on discuss.python.org
🌐 discuss.python.org
12
1
April 9, 2023
Python Class tutorial
Hi there i have completed a an exercise from a book and wanted you guys to have a look, I think its giving me back the results needed but i cant tell for sure if i have answered the questions rightly and the code i wrote is not error prone. better coding suggestions are welcome: “”" User ... More on discuss.python.org
🌐 discuss.python.org
3
0
April 29, 2023
Title: Struggling to Understand Python Classes – Any Simple Examples?
You actually already know the point of classes. You've used loads of them already. Every time you reference a method on a string or list for example, you're using a class. The only thing you haven't got the hang of yet is writing your own. (And what do you mean, how do init and self "actually work"? I'm sure you don't need to know the internal implementation details at this point. What are you asking?) More on reddit.com
🌐 r/learnpython
43
23
October 13, 2025
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
🌐
Python documentation
docs.python.org › 3 › tutorial › classes.html
9. Classes — Python 3.14.3 documentation
As discussed in A Word About Names and Objects, shared data can have possibly surprising effects involving mutable objects such as lists and dictionaries. For example, the tricks list in the following code should not be used as a class variable because just a single list would be shared by ...
🌐
Programiz
programiz.com › python-programming › class
Python Classes and Objects (With Examples)
In the above example, we have created two objects employee1 and employee2 of the Employee class. We can also define a function inside a Python class.
🌐
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. These materials are used within Google to introduce ...
🌐
HackerEarth
hackerearth.com › practice › python › object oriented programming › classes and objects i
Classes and Objects I Tutorials & Notes | Python | HackerEarth
>>> class Snake: ... name = "python" # set an attribute `name` of the class ... You can assign the class to a variable. This is called object instantiation. You will then be able to access the attributes that are present inside the class using the dot . operator. For example, in the Snake example, you can access the attribute name of the class Snake.
Find elsewhere
🌐
Python 101
python101.pythonlibrary.org › chapter11_classes.html
Chapter 11 - Classes — Python 101 1.0 documentation
The conditional statement above is a common way of telling Python that you only want to run the following code if this code is executed as a standalone file. If you had imported your module into another script, then the code underneath the conditional would not run. Anyway, if you run this code, you will create two instances of the Vehicle class: a car instance and a truck instance.
🌐
Real Python
realpython.com › python3-object-oriented-programming
Object-Oriented Programming (OOP) in Python – Real Python
December 15, 2024 - This funny-looking string of letters and numbers is a memory address that indicates where Python stores the Dog object in your computer’s memory. Note that the address on your screen will be different. Now instantiate the Dog class a second time to create another Dog object: ... The new Dog instance is located at a different memory address. That’s because it’s an entirely new instance and is completely unique from the first Dog object that you created. ... In this code, you create two new Dog objects and assign them to the variables a and b.
🌐
Real Python
realpython.com › python-classes
Python Classes: The Power of Object-Oriented Programming – Real Python
5 days ago - In the example above, circle_1 and circle_2 are separate instances of Circle. In other words, they’re two different and concrete circles, as you can conclude from the code’s output. Great! You already know how to create objects of an existing class by calling the class constructor with the required arguments. Now, how can you access the attributes and methods of a given class? That’s what you’ll learn in the next section. In Python...
🌐
Tutorialspoint
tutorialspoint.com › python › python_classes_objects.htm
Python - Classes and Objects
The below example demonstrates ... type. num = 20 print (type(num)) num1 = 55.50 print (type(num1)) s = "TutorialsPoint" print (type(s)) dct = {'a':1,'b':2,'c':3} print (type(dct)) def SayHello(): print ("Hello World") return print (type(SayHello)) When you execute ...
🌐
GitHub
github.com › rampal-punia › python-class-tutorial
GitHub - rampal-punia/python-class-tutorial: Python OOP tutorial with three examples(Point class, Animal Class and Rectangle Class) & one project (Student Management System)
Examples: _variable_name, _method_name for protected and __variable_name, __method_name for private variables and methods. Definition: Abstraction is used through encapsulation by hiding the internal functionality or implementation logic from ...
Starred by 11 users
Forked by 4 users
Languages   Python 100.0% | Python 100.0%
🌐
Python.org
discuss.python.org › python help
Python Class tutorial - Python Help - Discussions on Python.org
April 29, 2023 - Hi there i have completed a an exercise from a book and wanted you guys to have a look, I think its giving me back the results needed but i cant tell for sure if i have answered the questions rightly and the code i wrote is not error prone. better coding suggestions are welcome: “”" User Class: Test 1: 1 Make a class called User.
🌐
ScholarHat
scholarhat.com › home
Classes and Objects in Python (Explained with Examples)
September 10, 2025 - We can create multiple objects in a Python class easily. Below is an example you can try in Python Editor:
🌐
Texas Instruments
education.ti.com › en › bulletinboard › 2022 › python-coding-classes
Adding “Class” to Your Python Code | Texas Instruments
This blog introduces Python classes using both TI‑Nspire™ CX II and TI‑84 Plus CE Python graphing calculators. In the beginning ... As seen in the two partial examples above, I start a class using the keyword class followed by any class name and a colon: class balloon: and the rest of the class definition is indented.
🌐
Reddit
reddit.com › r/learnpython › title: struggling to understand python classes – any simple examples?
r/learnpython on Reddit: Title: Struggling to Understand Python Classes – Any Simple Examples?
October 13, 2025 -

Hello everyone

I am still a beginner to Python and have been going over the basics. Now, I am venturing into classes and OOP concepts which are quite tough to understand. I am a little unsure of..

A few things I’m having a hard time with:

  • What’s the real use of classes?

  • How do init and self actually work?

  • What the practical use of classes is?

Can anyone give a simple example of a class, like a bank account or library system? Any tips or resources to understand classes better would also be great.

Thanks!

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).

🌐
GitHub
github.com › Asabeneh › 30-Days-Of-Python › blob › master › 21_Day_Classes_and_objects › 21_classes_and_objects.md
30-Days-Of-Python/21_Day_Classes_and_objects/21_classes_and_objects.md at master · Asabeneh/30-Days-Of-Python
In the examples above, we have created an object from the Person class. However, a class without a constructor is not really useful in real applications. Let us use constructor function to make our class more useful. Like the constructor function in Java or JavaScript, Python has also a built-in init() constructor function.
Author   Asabeneh
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-classes-and-objects
Python Classes and Objects - GeeksforGeeks
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>. Take an example of using __str__() method to provide a readable string output for an object:
Published   1 week ago
🌐
w3resource
w3resource.com › python-exercises › class-exercises
Python Class - Exercises, Practice, Solution - w3resource
Note: There will be one solution for each input and do not use the same element twice. Input: numbers= [10,20,10,40,50,60,70], target=50 Output: 3, 4 · Difficulty: Medium. Company: Google, Facebook ...