簡體   English   中英

為什么無法設置類的某些屬性?

[英]Why setting some attributes of a class is not possible?

我試圖創建一個繼承自requests.Response的虛擬響應。 它將添加一個額外的屬性並覆蓋現有屬性:

import requests

class MyResponse(requests.Response):

    def __init__(self):
        super().__init__()
        self.hello = "world"
        self.ok = False

print(vars(MyResponse()))

添加self.hello很好,但是當我想將self.ok強制為一個值時,我得到:

Traceback (most recent call last):
  File "C:/Users/yop/.PyCharm2019.2/config/scratches/scratch.py", line 11, in <module>
    print(vars(MyResponse()))
  File "C:/Users/yop/.PyCharm2019.2/config/scratches/scratch.py", line 9, in __init__
    self.ok = False
AttributeError: can't set attribute

為什么有些屬性無法設置/覆蓋?

ok是一個性質requests.Response但它沒有制定者 ,因此不能設置。

相反,您可以覆蓋它並始終返回False (或True或您想要的任何值):

class MyResponse(requests.Response):
    def __init__(self):
        super().__init__()
        self.hello = "world"

    @property
    def ok(self):
        return False


或者,查看適當的mock解決方案,例如mock模塊。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM