函数返回自身的引用Python [英] Function returning reference to itself Python

查看:118
本文介绍了函数返回自身的引用Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是Python中的实际用法吗?

Does the following have 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


推荐答案

这是常见的做法,可能不是那么多的功能,但在OOP中广泛使用。基本上,每当你没有使用getter(一个返回对象属性的方法)或返回特定的东西时,没有 cost 来返回对象本身。但它允许压缩代码,如

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

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

或者,您必须编写

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

这不是世界末日,但它可以压缩代码而不会减少可读性,因此它是一件好事。

It's not the end of the world, but it allows to compress code without reducing readability, hence it is a nice thing.

以您的示例

第一个是直接和类似的,它允许压缩代码。第二个实际上不是我亲自做的事情,因为

The first one is straight forward and similar, it allows compression of code. The second one is actually not something I personally would do, because

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

在这个简单的例子中,没有理由为什么它应该表现得像这样并且可能混乱。

In this simple example, there is no reason why it should behave like that and might be confusing.

回到OOP

无论如何,在OOP中,当然你可以想象

Anyhow, in OOP, of course you could imagine

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()

会开门。这可能不是这种情况下最好的例子,但现在我只是为了表明有可能使用返回的其他对象。但是,最后一种情况可能会更好地完成:

would "open the door". This is probably not the best example for this scenario, but something I came along with right now just to show that there is potential use of returning "other objects". However, the last case would probably better be done by

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

这篇关于函数返回自身的引用Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆