我尝试创建我自己的从 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
是 property requests.Response
但它 has no setter所以不能设置。
相反,您可以覆盖它并始终返回 False
(或 True
或您想要的任何内容):
class MyResponse(requests.Response):
def __init__(self):
super().__init__()
self.hello = "world"
@property
def ok(self):
return False
或者,查看适当的模拟解决方案,例如 mock
模块。
关于python - 为什么不能设置类的某些属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57312396/