>>> f = object()# It's obvIoUs behavior:>>> f.fooTraceback (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.
总结以上是内存溢出为你收集整理的Python如何区分显式传递None作为内置函数中的参数全部内容,希望文章能够帮你解决Python如何区分显式传递None作为内置函数中的参数所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)