Open In App

Define and Call Methods in a Python Class

Last Updated : 14 Feb, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In object-oriented programming, a class is a blueprint for creating objects, and methods are functions associated with those objects. Methods in a class allow you to define behavior and functionality for the objects created from that class. Python, being an object-oriented programming language, provides a straightforward syntax for defining and calling methods within a class. In this article, we will explore the concepts of methods in a class in Python and will see how to define and call methods in a class with examples and explanations.

What are Methods in a Class in Python?

A method in a class is a function that is associated with an object. It defines the behavior and actions that objects of the class can perform. Methods are essential for encapsulating functionality and promoting code reusability. They are defined inside a class and can access the attributes (variables) of the class.

Syntax of Method

class ClassName:

def method_name(self, parameter1, parameter2, ...):

# Method body - code goes here

# Creating an object of the class

object_name = ClassName()

# Calling a method on the object

object_name.method_name(argument1, argument2, ...)

Define And Call Methods In A Class In Python

Let's look at how to define and call methods in a class with the help of examples.

Example 1: Simple Class with a Method

In this example, we define a class GeeksClass with a method say_hello. The say_hello method simply prints the message "Hello, Geeks!" when called. We then create an instance of the class (geeks_object) and call the say_hello method on that instance.

Python3
class GeeksClass:
    def say_hello(self):
        print("Hello, Geeks!")

# Creating an object of GeeksClass
geeks_object = GeeksClass()

# Calling the say_hello method
geeks_object.say_hello()

Output
Hello, Geeks!

Example 2: Class with Parameterized Method

In this example, we define a Calculator class with an add method that takes two parameters (num1 and num2) and returns their sum. We create an instance of the Calculator class (calculator_object) and call the add method with arguments 5 and 7.

Python3
class Calculator:
    def add(self, num1, num2):
        return num1 + num2

# Creating an object of Calculator
calculator_object = Calculator()

# Calling the add method with parameters
result = calculator_object.add(5, 7)
print("Result of addition:", result)

Output
Result of addition: 12

Conclusion

Defining and calling methods in a class in Python is fundamental to object-oriented programming. Methods enable us to encapsulate functionality within objects, promoting code organization and reusability. By understanding how to define and call methods, you can build powerful and modular code structures in Python. As demonstrated with GeeksforGeeks examples, these concepts are not only fundamental but also applicable in real-world coding scenarios.


Next Article
Article Tags :
Practice Tags :

Similar Reads

How to Define and Call a Function in Python
In Python, defining and calling functions is simple and may greatly improve the readability and reusability of our code. In this article, we will explore How we can define and call a function. Example: [GFGTABS] Python # Defining a function def fun(): print("Welcome to GFG") # calling a function fun() [/GFGTABS]Let's understand defining a
3 min read
Is Python call by reference or call by value
Python utilizes a system, which is known as "Call by Object Reference" or "Call by assignment". If you pass arguments like whole numbers, strings, or tuples to a function, the passing is like a call-by-value because you can not change the value of the immutable objects being passed to the function. Passing mutable objects can be considered as call
5 min read
Call a Class Method From another Class in Python
In object-oriented programming, classes play a pivotal role in organizing and structuring code. Python, being an object-oriented language, allows the creation of classes and their methods to facilitate code modularity and reusability. One common scenario in programming is the need to call a method from one class within another class. In this articl
3 min read
What is the Proper Way to Call a Parent's Class Method Inside a Class Method?
In object-oriented programming, calling a parent class method inside a class method is a common practice, especially when you want to extend or modify the functionality of an inherited method. This process is known as method overriding. Here's how to properly call a parent class method inside a class method in Python. Basic Syntax Using super()The
3 min read
Python: Call Parent class method
A class is a user-defined blueprint or prototype from which objects are created. 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. Example: # Python program to demonstrate # classes class cls: # Constructor def __init__(self, fname,
4 min read
How to Define an Auto Increment Primary Key in PostgreSQL using Python?
Prerequisite: PostgreSQL Python has various database drivers for PostgreSQL. Currently, most used version is psycopg2 because it fully implements the Python DB-API 2.0 specification. The psycopg2 provides many useful features such as client-side and server-side cursors, asynchronous notification and communication, COPY command support, etc. Install
3 min read
Define Custom Exceptions in Python
In Python, exceptions occur during the execution of a program that disrupts the normal flow of the program’s instructions. When an error occurs, Python raises an exception, which can be caught and handled using try and except blocks. Here’s a simple example of handling a built-in exception: [GFGTABS] Python try: result = 10 / 0 except ZeroDivisionE
3 min read
Explicitly define datatype in a Python function
Unlike other languages Java, C++, etc. Python is a strongly, dynamically-typed language in which we don't have to specify the data type of the function's return value and its arguments. It relates types with values instead of names. The only way to specify data of specific types is by providing explicit datatypes while calling the functions. Exampl
3 min read
Store Functions in List and Call in Python
In Python, a list of functions can be created by defining the tasks and then adding them to a list. Here’s a simple example to illustrate how to do this: [GFGTABS] Python def say_hello(): return "Hello!" #Store a function "say_hello" in a list greetings = [say_hello] #Call the first function in the list print(greetings[0]()) [/G
3 min read
Define Colors in a Figure Using Plotly Graph Objects and Plotly Express
Whether you use Plotly Graph Objects or Plotly Express, defining colors in your figures allows you to create visually appealing and informative visualizations. Plotly's flexibility in color customization helps you highlight important data points, differentiate categories, and make your charts more engaging in Python. Plotly Graph ObjectsPlotly Grap
3 min read
Subclass and methods of Shelve class in Python
Shelve is a module in Python's standard library which can be used as a non-relational database. The key difference between a dbm and shelve is that shelve can serve its values as any arbitrary object which can be handled by pickle module while in dbm database we can only have standard datatypes of Python as its database values. The key in shelve is
4 min read
call() decorator in Python
Python Decorators are important features of the language that allow a programmer to modify the behavior of a class. These features are added functionally to the existing code. This is a type of metaprogramming when the program is modified at compile time. The decorators can be used to inject modified code in functions or classes. The decorators all
3 min read
Decorator to print Function call details in Python
Decorators in Python are the design pattern that allows the users to add new functionalities to an existing object without the need to modify its structure. Decorators are generally called before defining a function the user wants to decorate. Example: # defining a decorator def hello_decorator(func): # inner1 is a Wrapper function in # which the a
3 min read
Call a function by a String name - Python
In this article, we will see how to call a function of a module by using its name (a string) in Python. Basically, we use a function of any module as a string, let's say, we want to use randint() function of a random module, which takes 2 parameters [Start, End] and generates a random value between start(inclusive) and end(inclusive). Here, we will
3 min read
How to Call a C function in Python
Have you ever came across the situation where you have to call C function using python? This article is going to help you on a very basic level and if you have not come across any situation like this, you enjoy knowing how it is possible.First, let's write one simple function using C and generate a shared library of the file. Let's say file name is
2 min read
Python - Call function from another function
Prerequisite: Functions in Python In Python, any written function can be called by another function. Note that this could be the most elegant way of breaking a problem into chunks of small problems. In this article, we will learn how can we call a defined function from another function with the help of multiple examples.  What is Calling a Function
5 min read
Call column name when it is a timestamp in Python
Handling timestamp columns efficiently is crucial for many data science and engineering tasks. Timestamp columns often require specific operations like parsing, formatting, and time-based filtering. In this article, we will explore three good code examples of how to call and manipulate timestamp columns using different methods and libraries. Callin
3 min read
How to call a function in Python
Python is an object-oriented language and it uses functions to reduce the repetition of the code. In this article, we will get to know what are parts, How to Create processes, and how to call them. In Python, there is a reserved keyword "def" which we use to define a function in Python, and after "def" we give the name of the function which could b
5 min read
Retrieving the output of subprocess.call() in Python
The subprocess.call() function in Python is used to run a command described by its arguments. Suppose you need to retrieve the output of the command executed by subprocess.call(). In that case, you'll need to use a different function from the subprocess module, such as subprocess.run(), subprocess.check_output(), or subprocess.Popen(). Introduction
4 min read
Python - Call function from another file
Given a Python file, we need to call a function in it defined in any other Python file. Example: Suppose there is a file test.py which contains the definition of the function displayText(). #test.py>def displayText(): print( "Geeks 4 Geeks!")We need to call the function displayText() in any other Python file such that wherever we call displayTex
5 min read
Fix: "SyntaxError: Missing Parentheses in Call to 'print'" in Python
In Python, if we see the "SyntaxError: Missing Parentheses in Call to 'print'" error, it means we forgot to use parentheses around what we want to print. This is the most common error that we encounter when transitioning from Python 2 to Python 3. This error occurs due to a significant change in how the print statement works between Python2 and Pyt
3 min read
How to Make API Call Using Python
APIs (Application Programming Interfaces) are an essential part of modern software development, allowing different applications to communicate and share data. Python provides a popular library i.e. requests library that simplifies the process of calling API in Python. In this article, we will see how to make API calls in Python. Make API Call in Py
3 min read
How to Call Multiple Functions in Python
In Python, calling multiple functions is a common practice, especially when building modular, organized and maintainable code. In this article, we’ll explore various ways we can call multiple functions in Python. The most straightforward way to call multiple functions is by executing them one after another. Python makes this process simple and intu
3 min read
Using User Input to Call Functions - python
input() function allows dynamic interaction with the program. This input can then be used to call specific functions based on the user's choice . Let’s take a simple example to call function based on user's input . Example: [GFGTABS] Python def add(x, y): return x + y # Add def sub(x, y): return x - y # Subtract a = input() # Input if a == "ad
2 min read
Define Node position in Sankey Diagram in plotly
Plotly is a Python library which is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library. Sankey Diagram is used to visualize the flow by
1 min read
How to define a mathematical function in SymPy?
SymPy is a Python Library that makes 'Symbolic Computation' possible in Python. Mathematical Functions using SymPy We can define mathematical functions by using SymPy in Python. There are two types of functions that we can define with the help of SymPy: 'Undefined Functions' and 'Custom Functions'. Undefined Functions: A programmer can create 'Unde
4 min read
How to Define Two Fields "Unique" as Couple in Django
In many applications, you might encounter scenarios where you need to ensure that a pair of fields in a database model must be unique together. For example, if you have a Booking model in a restaurant reservation system, you may want to ensure that the combination of table_number and reservation_time is unique, preventing double bookings for the sa
2 min read
Customize your Python class with Magic or Dunder methods
The magic methods ensure a consistent data model that retains the inherited feature of the built-in class while providing customized class behavior. These methods can enrich the class design and can enhance the readability of the language. So, in this article, we will see how to make use of the magic methods, how it works, and the available magic m
13 min read
Accessing Attributes and Methods in Python
Attributes of a class are function objects that define corresponding methods of its instances. They are used to implement access controls of the classes. Attributes of a class can also be accessed using the following built-in methods and functions : getattr() - This function is used to access the attribute of object. hasattr() - This function is us
3 min read
Python | Float type and its methods
The float type in Python represents the floating point number. Float is used to represent real numbers and is written with a decimal point dividing the integer and fractional parts. For example, 97.98, 32.3+e18, -32.54e100 all are floating point numbers. Python float values are represented as 64-bit double-precision values. The maximum value any fl
3 min read
  翻译: