为什么无法设置类的某些属性?

WoJ*_*WoJ 2 python attributes class python-3.x python-requests

我试图创建自己的继承自的虚拟响应requests.Response。它将添加一个额外的属性并覆盖现有属性:

import requests

class MyResponse(requests.Response):

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

print(vars(MyResponse()))
Run Code Online (Sandbox Code Playgroud)

添加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
Run Code Online (Sandbox Code Playgroud)

为什么有些属性无法设置/覆盖?

Dee*_*ace 6

ok是的属性requests.Response没有设置器,因此无法设置。

相反,您可以覆盖它并始终返回False(或返回True任何您想要的值):

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

    @property
    def ok(self):
        return False
Run Code Online (Sandbox Code Playgroud)


或者,查看适当的mock模拟解决方案,例如模块。