加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Python如何区分显式传递None作为内置函数中的参数

发布时间:2020-12-20 12:09:04 所属栏目:Python 来源:网络整理
导读:我试验了下一个代码: f = object()# It's obvious behavior: f.fooTraceback (most recent call last): File "stdin",line 1,in moduleAttributeError: 'object' object has no attribute 'foo'# However,the next one is surprising me! getattr(f,'foo')T
我试验了下一个代码:

>>> 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>",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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读