首页 > 编程知识 正文

python中getattr函数,python中返回结果为true

时间:2023-05-06 07:18:44 阅读:163373 作者:1268

whydoeshasattrsaythattheinstancedoesn ' thavea执着的猎豹attribute?

类a (object ) :

. @property

. def执拗的猎豹(self ) :

. ErrorErrorError

.

a=A () ) )。

Hasattr(a,'执着的猎豹') ) ) ) ) ) ) ) ) ) ) )。

I expected:

Hasattr(a,'执着的猎豹') ) ) ) ) ) ) ) ) ) ) )。

the python2implementationofhasattrisfairlynaive,itjusttriestoaccessthatattributeandseeewhetheritraisesanexceptionornot。

Unfortunately,thismeansthatanyunhandledexceptionsinsidepropertieswillgetswallowed,anderrorsinthatcodecangetlost.toaddinst when hasattr eats the exception,itwillalsoreturnanincorrectanswer (heretheattributea .执着的猎豹does exist,sotheresultshouldhaver

In python3.2,thebehaviourhasbeencorrected :

Hasattr(object,name ) )。

theargumentsareanobjectandastring.theresultistrueifthestringisthenameoftheobject’sattributes,false if not.(thisisimplemplemp ) name ) andseeingwhetheritraisesanattributeerrornot.) )。

The fix is here,butunfortunatelythatchangedidn ' t backport。

ifthe python2behaviourcausestroubleforyou,consider to avoid using hasattr; insteadyoucanuseatry/exceptaroundgetattr,catchingonlytheattributeerrorexceptionandlettinganyothersraiseunhandled。

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。