python - 为什么不能设置类的某些属性?

标签 python python-3.x class attributes python-requests

我尝试创建我自己的从 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

为什么有些属性不能设置/覆盖?

最佳答案

okproperty 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/

相关文章:

php - 类外定义的方法?

java - 调用方法没有得到结果

python - 之前的字符串\r 未显示

python - 绘制图像的傅里叶变换时出现问题。 "ValueError: x and y can be no greater than 2-D, but have shapes (2592,) and (2592, 1, 3)"

python - 如何包装按类型重载的函数?

python - 错误: ImportError: No module named docx --> using nodeJS python-shell package to control python script

Java获取类的路径

python - 小写与小写+标题版本的特定字数不同

python - 在 Snakemake 脚本中使用 argparse

python - 在python中从键盘读取原始输入