A function is a block of code that performs a specific task. It is defined using the def keyword in Python. For example, the following code defines a function called square that takes a number as input and returns the square of that number: def square(number): return number * number print(square(5)) A class is a blueprint for creating objects. It defines the properties and methods of an object. For example, the following code defines a class called Rectangle that has two properties, width and height, and one method, area. The area method calculates the area of the rectangle. class Rectangle: def __init__(self, width, height): self.width = width self.height = height def area(self): return self.width * self.height rectangle = Rectangle(10, 20) print(rectangle.area()) The main difference between a function and a class is that a function is a reusable block of code, while a class is a blueprint for creating objects. Functions are typically used to perform specific tasks, while classes are used to create objects that have properties and methods. So, when should you use a function and when should you use a class? Here are some general guidelines: Use a function when you need to perform a specific task that does not need to be associated with an object. Use a class when you need to create an object that has properties and methods. Here is a clear example of when to use a function and when to use a class: Let's say you want to write a function that calculates the factorial of a number. You would use a function because you do not need to create an object to store the factorial value. Let's say you want to write a program that manages a list of contacts. You would use a class because you need to create objects to represent each contact. The class would have properties to store the contact's name, email address, and phone number. The class would also have methods to add, remove, and update contacts. I hope this helps! Answer from martynrbell on reddit.com
๐ŸŒ
Python documentation
docs.python.org โ€บ 3 โ€บ tutorial โ€บ classes.html
9. Classes โ€” Python 3.14.3 documentation
Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to it for maintaining its state.
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ python_classes.asp
Python Classes/Objects
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.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ what is the difference between a class and a function? when to use each one?
r/learnpython on Reddit: What is the difference between a class and a function? When to use each one?
July 11, 2023 -

Hi! I have very less time working with python and now I am going through classes, but until now they look kind of similar to definition of functions. When should I use one and when another? Is there a clear example for it?

Thanks a lot!

Top answer
1 of 14
74
A function is a block of code that performs a specific task. It is defined using the def keyword in Python. For example, the following code defines a function called square that takes a number as input and returns the square of that number: def square(number): return number * number print(square(5)) A class is a blueprint for creating objects. It defines the properties and methods of an object. For example, the following code defines a class called Rectangle that has two properties, width and height, and one method, area. The area method calculates the area of the rectangle. class Rectangle: def __init__(self, width, height): self.width = width self.height = height def area(self): return self.width * self.height rectangle = Rectangle(10, 20) print(rectangle.area()) The main difference between a function and a class is that a function is a reusable block of code, while a class is a blueprint for creating objects. Functions are typically used to perform specific tasks, while classes are used to create objects that have properties and methods. So, when should you use a function and when should you use a class? Here are some general guidelines: Use a function when you need to perform a specific task that does not need to be associated with an object. Use a class when you need to create an object that has properties and methods. Here is a clear example of when to use a function and when to use a class: Let's say you want to write a function that calculates the factorial of a number. You would use a function because you do not need to create an object to store the factorial value. Let's say you want to write a program that manages a list of contacts. You would use a class because you need to create objects to represent each contact. The class would have properties to store the contact's name, email address, and phone number. The class would also have methods to add, remove, and update contacts. I hope this helps!
2 of 14
10
Classes are good at keeping state, and grouping together relevant functions that modify that state. If you have user data, name, address, phone number, date they joined, password, list of friends, etc. Having a function that adds a new friend to the list of friends would require lots of arguments to the function and complex data structures. add_new_friend(all_users_data, user_name, users_friends_list, friend_name) Or you can make a class that handles everything related to that user and can access all user related data, and would only need the "who to friend". user.add_friend(friend)
๐ŸŒ
Codearmo
codearmo.com โ€บ python-tutorial โ€บ object-orientated-programming-functions
Adding Functions to Python Classes | Codearmo
March 28, 2025 - We can add a mix of instance bound functions and normal functions as defined at the beginning of the document. Below we add a method that prints the current academic year. import datetime as dt class Student: def __init__(self, first, last, age, major): self.first = first self.last = last self.age = age self.major = major self.courses = [] def profile(self): print(f"Student name {self.first + ' ' + self.last}") print(f"Student age: {self.age}") print(f"Major: {self.major}") def enrol(self, course): self.courses.append(course) print(f"enrolled {self.first} in {course}") def show_courses(self): print(f"{self.first + '' + self.last} is taking the following courses") for course in self.courses: print(course) def academic_year(): now = dt.datetime.now() s = now.year, now.year -1 print(f"Current academic year is { str(s[0]) + '/' + str(s[1]) }")
๐ŸŒ
Cisco Press
ciscopress.com โ€บ articles โ€บ article.asp
Python Functions, Classes, and Modules
November 9, 2022 - Think of a class as a tool you use to create your own data structures that contain information about something; you can then use functions (methods) to perform operations on the data you describe. A class models how something should be defined and represents an idea or a blueprint for creating ...
๐ŸŒ
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
Top answer
1 of 5
38

you have to use self as the first parameters of a method

in the second case you should use

class MathOperations:
    def testAddition (self,x, y):
        return x + y

    def testMultiplication (self,a, b):
        return a * b

and in your code you could do the following

tmp = MathOperations()
print tmp.testAddition(2,3)

if you use the class without instantiating a variable first

print MathOperation.testAddtion(2,3)

it gives you an error "TypeError: unbound method"

if you want to do that you will need the @staticmethod decorator

For example:

class MathsOperations:
    @staticmethod
    def testAddition (x, y):
        return x + y

    @staticmethod
    def testMultiplication (a, b):
        return a * b

then in your code you could use

print MathsOperations.testAddition(2,3)
2 of 5
15

disclaimer: this is not a just to the point answer, it's more like a piece of advice, even if the answer can be found on the references

IMHO: object oriented programming in Python sucks quite a lot.

The method dispatching is not very straightforward, you need to know about bound/unbound instance/class (and static!) methods; you can have multiple inheritance and need to deal with legacy and new style classes (yours was old style) and know how the MRO works, properties...

In brief: too complex, with lots of things happening under the hood. Let me even say, it is unpythonic, as there are many different ways to achieve the same things.

My advice: use OOP only when it's really useful. Usually this means writing classes that implement well known protocols and integrate seamlessly with the rest of the system. Do not create lots of classes just for the sake of writing object oriented code.

Take a good read to this pages:

  • http://docs.python.org/reference/datamodel.html
  • http://docs.python.org/tutorial/classes.html

you'll find them quite useful.

If you really want to learn OOP, I'd suggest starting with a more conventional language, like Java. It's not half as fun as Python, but it's more predictable.

๐ŸŒ
Python Morsels
pythonmorsels.com โ€บ class-function-and-callable
Callables: Python's "functions" are sometimes classes - Python Morsels
May 25, 2022 - Whether a callable is a class or a function is often just an implementation detail. It's not really a mistake to refer to property or redirect_stdout as functions because they may as well be functions. We can call them to get back a useful object, and that's what we care about. Python's "call" syntax, those (...) parentheses, can create a class instance or call a function.
Find elsewhere
๐ŸŒ
W3Schools
w3schools.com โ€บ PYTHON โ€บ python_class_methods.asp
Python Class Methods
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 ... Methods are functions that belong to a class.
๐ŸŒ
Duke University
people.duke.edu โ€บ ~ccc14 โ€บ sta-663 โ€บ FunctionsSolutions.html
Functions are first class objects โ€” Computational Statistics in Python 0.1 documentation
In Python, functions behave like any other object, such as an int or a list. That means that you can use functions as arguments to other functions, store functions as dictionary values, or return a function from another function.
๐ŸŒ
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 - Class methods are defined inside a class, and it is pretty similar to defining a regular function. Like, inside an instance method, we use the self keyword to access or modify the instance variables.
๐ŸŒ
Programiz
programiz.com โ€บ python-programming โ€บ methods โ€บ built-in โ€บ classmethod
Python classmethod()
Become a certified Python programmer. Try Programiz PRO! ... The classmethod() method returns a class method for the given function.
๐ŸŒ
Mimo
mimo.org โ€บ glossary โ€บ python โ€บ class
Python Class: Syntax and Examples [Python Tutorial]
Start your coding journey with Python. Learn basics, data types, control flow, and more ... # 1. Define the class (the blueprint) class Dog: # The constructor method to initialize new objects def __init__(self, name, age): self.name = name # Attribute for the dog's name self.age = age # Attribute for the dog's age # A method (a function inside the class) def bark(self): return f"{self.name} says woof!"
๐ŸŒ
Real Python
realpython.com โ€บ python-classes
Python Classes: The Power of Object-Oriented Programming โ€“ Real Python
December 15, 2024 - In Python, attributes are variables ... methods to refer to the different behaviors that objects will show. Methods are functions that you define within a class....
๐ŸŒ
Codecademy
codecademy.com โ€บ learn โ€บ cspath-python-objects โ€บ modules โ€บ cspath-python-classes โ€บ cheatsheet
Python Objects: Python: Classes Cheatsheet | Codecademy
In Python, a class is a template for a data type. 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.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ classmethod-in-python
classmethod() in Python - GeeksforGeeks
July 11, 2025 - In Python, the classmethod() function is used to define a method that is bound to the class and not the instance of the class. This means that it can be called on the class itself rather than on instances of the class.
Top answer
1 of 2
6

There is a function type, but there is no built-in name for it. You can find another reference there under the types module:

>>> import types
>>> def T1():
...     pass
...     
>>> T1.__class__ is types.FunctionType
True
>>> print(repr(types.FunctionType))
<class 'function'>

So, the only difference here is that function is not a built-in name, unlike names such as int. If you want that name in your namespace for some reason, you can just bind it:

>>> function = type(lambda: 0)
>>> function
<class 'function'>
2 of 2
1

Think of it this way. Say you create your own metaclass (class of a class), and a subclass of your metaclass (which is itself just a class):

>>> class MyMeta(type): # <-- a custom metaclass, similar to function
        pass

>>> print(MyMeta.__name__)
MyMeta
>>> print(__class__)
<class 'type'>

>>> class MyClass(metaclass = MyMeta):
        pass
>>> print(MyClass.__class__)
<class 'MyMeta'>

Now, we will delete the identifier MyMeta:

>>> del MyMeta

Can you still get to the metaclass object that was represented by MyMeta although MyMeta has been deleted? Sure:

>>> print(MyClass.__class__)
<class 'MyMeta'>

So there is still a reference to the metaclass object in the MyClass dict.

However, the name MyMeta is now invalid, since it was deleted:

>>> class MyClassTwo(metaclass = MyMeta):
        pass
NameError!!
>>> print(MyMeta.__name__)
NameError!!
>>> print(MyMeta)
NameError!!

IMPORTANT: The metaclass name has been deleted, not the metaclass object itself.

Therefore you can still access the metaclass object this way:

>>> class MyClassTwo(metaclass = MyClass.__class__):
        pass

So it is with the function name (which is itself kind of like a built-in metaclass; i.e., it is the class, or type, of function objects)- by default, the name function doesn't exist in an interactive Python session. But the object does still exist. You can access it this way:

>>> def f(): pass
>>> f.__class__.__class__
<class 'type'>

And if you like, you can even go ahead and assign the name function to the function <class 'type'> object (although there's not much reason to do that):

>>> function  = f.__class__
>>> print(function)
<class 'function'>
>>> print(function.__class__)
<class 'type'>
๐ŸŒ
Learn Python
learnpython.org โ€บ en โ€บ Classes_and_Objects
Classes and Objects - Learn Python - Free Interactive Python Tutorial
The above would print out the message, "This is a message inside the class." The __init__() function, is a special function that is called when the class is being initiated.