Python return function

Is there any practical use in Python?

>>> def a(n):
        print(n)
        return a

Or even:

>>> def a(n):
        print(n)
        return b
>>> def b(n):
        print(n+3)
        return a
+4
source share
1 answer

This is a common practice, perhaps not so much with functions as it is widely used in OOP. Basically, whenever you do not use getter (a method that returns the properties of an object) or returns something specific, there is no cost to returning the object itself. But it allows you to compress the code, as in

house = House()
exits = house.setDoors(2).setWindows(4).getNumberOfEmergencyExitsRequired()

Alternatively you will have to write

house = House()
house.setDoors(2)
house.setWindows(4)
exits = house.getNumberOfEmergencyExistsRequired()

This is not the end of the world, but it allows you to compress the code without reducing readability, so this is a good thing.

To your examples

- , . - , ,

a(3)(5) == a(3); b(5)

, , .

, , ,

class House(object):
    def addDoorByColor(self, doorColor):
        door = new Door()
        door.setColor(doorColor)
        self.door = door
        return self.door

house = House(); 
house.addDoorByColor('red').open()

" ". , , , , " ". , ,

door = new Door('red')
house.addDoor(door)
door.open()
+1

Source: https://habr.com/ru/post/1541227/


All Articles