return — Advanced Playground
Exits a function and optionally sends a value back to the caller
Python Playground
def make_adder(n):
def adder(x):
return x + n
return adder
add5 = make_adder(5)
add10 = make_adder(10)
print(add5(3))
print(add10(3))
# Returning a class
def make_class(name, fields):
def init(self, **kwargs):
for f in fields:
setattr(self, f, kwargs.get(f))
def repr_(self):
vals = ", ".join(f"{f}={getattr(self, f)!r}" for f in fields)
return f"{name}({vals})"
cls = type(name, (), {"__init__": init, "__repr__": repr_})
return cls
Point = make_class("Point", ["x", "y"])
p = Point(x=1, y=2)
print(p)
Output
Click "Run" to execute your code
Functions are first-class objects, so you can return functions (closures), classes, or any other object from a function.
Challenge
Try modifying the code above to explore different behaviors. Can you extend the example to handle a new use case?