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。