编程语言
首页 > 编程语言> > Python如何区分显式传递None作为内置函数中的参数

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)

然后我在PyCharm IDE中找到了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()(可能还有其他函数)的场景?是否可以完全在客户端代码中执行类似的操作?

解决方法:

正如@scytale所说,getattr的伪签名并不完全符合它的实现.我已经看到尝试在纯Python中复制行为,看起来像这样:

class MyObject(object):
    __marker = object()

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

换句话说,使用调用者无法轻易提供的标记值来检查是否没有给出默认值而不是None.

标签:python,python-internals,built-in
来源: https://codeday.me/bug/20190716/1475953.html