Python如何区分内建函数中显式传递的None作为参数 [英] How does Python distinguish explicitly passed None as argument in built-ins

查看:209
本文介绍了Python如何区分内建函数中显式传递的None作为参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了下一个代码:

>>> f = object()

# It's obvious behavior:
>>> f.foo
Traceback (most recent call last):       
  File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'foo'

# However, the next one is surprising me!
>>> getattr(f, 'foo')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'foo'

# And this one returns None as expected:
>>> getattr(f, 'foo', None)

然后我发现了<$ c的伪签名PyCharm IDE中的$ c> getattr():

def getattr(object, name, default=None): # known special case of getattr
    """
    getattr(object, name[, default]) -> value

    Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.
    When a default argument is given, it is returned when the attribute doesn't
    exist; without it, an exception is raised in that case.
    """
    pass

我的问题是python如何区分这两个内部使用 getattr()(可能还有其他功能)的场景?

My question is how does python distinguish this two scenarios of using getattr() (and maybe other functions) internally? And is it possible to do something similar entirely in the client side code?

推荐答案

就像@scytale所说的那样,是否有可能在客户端代码中做类似的事情? getattr 与其实现并不完全对应。我见过尝试在纯Python中复制行为的尝试,如下所示:

As @scytale said, the pseudo-signature of getattr doesn't quite correspond to its implementations. I've seen attempts to replicate the behaviour in pure Python that look something like this:

class MyObject(object):
    __marker = object()

    def getvalue(key, default=__marker):
        ...
        if key is __marker:
             # no value supplied for default
             ....

换句话说,使用呼叫者无法使用的标记值轻松提供以检查是否没有默认值,而不是

In other words, use a marker value that a caller cannot easily supply to check if no value was given as the default rather than None.

这篇关于Python如何区分内建函数中显式传递的None作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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