前哨对象及其应用? [英] Sentinel object and its applications?

查看:51
本文介绍了前哨对象及其应用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在python中内置的 object()返回一个哨兵对象.我很好奇它是什么,但主要是它的应用程序.

I know in python the builtin object() returns a sentinel object. I'm curious to what it is, but mainly its applications.

推荐答案

object 是python 3中所有其他类都继承的基类.旧的对象.但是,对象的 identity 可能有用.例如, iter 函数采用 sentinel 参数,指示何时停止终止.我们可以为此提供一个object().

object is the base class that all other classes inherit from in python 3. There's not a whole lot you can do with a plain old object. However an object's identity could be useful. For example the iter function takes a sentinel argument that signals when to stop termination. We could supply an object() to that.

sentinel = object()

def step():
    inp = input('enter something: ')
    if inp == 'stop' or inp == 'exit' or inp == 'done':
        return sentinel
    return inp

for inp in iter(step, sentinel):
    print('you entered', inp)

这将要求输入,直到用户键入停止,退出或完成.我不确定何时带有哨兵的 iter 比生成器更有用,但我想还是很有趣.

This will ask for input until the user types stop, exit, or done. I'm not exactly sure when iter with a sentinel is more useful than a generator, but I guess it's interesting anyway.

我不确定这是否能回答您的问题.需要明确的是,这只是 object 的可能应用.从根本上讲,它在python语言中的存在与将其用作哨兵值无关(据我所知).

I'm not sure if this answers your question. To be clear, this is just a possible application of object. Fundamentally its existence in the python language has nothing to do with it being usable as a sentinel value (to my knowledge).

这篇关于前哨对象及其应用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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