为什么hasattr在使用@property方法的类和实例上表现不同?

时间:2019-03-12 10:01:40

标签: python python-decorators readonly-attribute writeonly

我在课堂上使用SELECT * FROM PlacementDetail_Temp PDT LEFT JOIN dbo.[Authorization] AUTH on AUTH.PlacementDetailID = PDT.PlacementDetailID and AUTH.PayorID = @PayorID LEFT JOIN dbo.Provider SP_as_PR on SP_as_PR.ProviderID in (Select PR.ProviderID from dbo.Provider PR JOIN dbo.ProviderSponsor PS ON PR.ProviderID = PS.ProviderID and PS.SponsorID = AUTH.SponsorID where IsSponsor = 'True' ) 实现了只写属性。奇怪的是,@property在具有此属性的类和相应实例上的行为不同。

hasattr
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import UserMixin


class User(Base, UserMixin):
    # codes omitted...

    @property
    def password(self):
        raise AttributeError("password is a write-only attribute!")

    @password.setter
    def password(self, password):
        self.password_hash = generate_password_hash(password)

    def verify_password(self, password):
        return check_password_hash(self.password_hash, password)

根据In [6]: hasattr(User,'password') Out[6]: True In [7]: u1=User() In [9]: hasattr(u1,'password') Out[9]: False In [12]: getattr(User,'password') Out[12]: <property at 0x1118a84a8> In [13]: getattr(u1,'password') --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-13-b1bb8901adc7> in <module> ----> 1 getattr(u1,'password') ~/workspace/python/flask_web_development/fisher/app/models.py in password(self) 82 @property 83 def password(self): ---> 84 raise AttributeError("password is a write-only attribute!") 85 86 @password.setter AttributeError: password is a write-only attribute! 的结果,getattr尝试执行该方法并引发错误,而getattr(u1, 'password')不执行getattr(User, 'password')方法。他们为什么表现不同?

0 个答案:

没有答案