Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to get the return value from a function in a class in Python?
The following code shows how to get return value from a function in a Python class. When a method in a class uses the return statement, you can capture and use that value by calling the method on a class instance.
Basic Example
Here's a simple class that demonstrates returning values from methods ?
class Score():
def __init__(self):
self.score = 0
self.num_enemies = 5
self.num_lives = 3
def setScore(self, num):
self.score = num
def getScore(self):
return self.score
def getEnemies(self):
return self.num_enemies
def getLives(self):
return self.num_lives
# Create an instance and use the methods
s = Score()
s.setScore(9)
print(s.getScore())
print(s.getEnemies())
print(s.getLives())
9 5 3
Storing Return Values
You can store the returned values in variables for later use ?
class Calculator:
def add(self, a, b):
return a + b
def multiply(self, a, b):
return a * b
calc = Calculator()
# Store return values in variables
sum_result = calc.add(10, 5)
product_result = calc.multiply(4, 3)
print(f"Sum: {sum_result}")
print(f"Product: {product_result}")
Sum: 15 Product: 12
Using Return Values Directly
Return values can be used directly in expressions or other function calls ?
class MathOperations:
def square(self, x):
return x ** 2
def cube(self, x):
return x ** 3
math_ops = MathOperations()
# Use return values directly in calculations
result = math_ops.square(5) + math_ops.cube(2)
print(f"5² + 2³ = {result}")
# Use in conditional statements
if math_ops.square(4) > 10:
print("Square of 4 is greater than 10")
5² + 2³ = 33 Square of 4 is greater than 10
Conclusion
To get return values from class methods, simply call the method on an instance and either store the result in a variable or use it directly. The return statement in the method makes the value available to the caller.
Advertisements
