【问题标题】:Why is this python property not recognised [closed]为什么这个 python 属性无法识别[关闭]
【发布时间】:2023-01-12 21:54:13
【问题描述】:

我通常不使用 python 属性,但最近有理由这样做。 我有以下代码:

class my_object:
    @property
    def changed(self):
        return self._changed

    @property
    def name(self):
        return self._name

    @name.setter
    def name(self, name_string: str = ""):
        self._changed = True
        self._name = name_string

    @property
    def description(self):
        return self._description

    @description.setter
    def description(self, description_string: str = ""):
        self._changed = True
        self._description = description_string

    def __int__(self, *args, **kwargs):
        self._changed = False
        self._name = ""
        self._description = ""


test_object = my_object()
print("CHANGED ", test_object.changed)
print("NAME ", test_object.name)
print("DESCRIPTION ", test_object.description)

test_object.name = "John Doe"
test_object.description = "This is John's object"

print("CHANGED ", test_object.changed)
print("NAME ", test_object.name)
print("DESCRIPTION ", test_object.description)

当我运行脚本时,我收到消息:

AttributeError: 'my_object' object has no attribute '_changed'. Did you mean: 'changed'?

但我真的看不出我做错了什么;它必须是基本的,但我看不到它。 也许有人会告诉我 谢谢

【问题讨论】:

  • 打字错误:__init__不是__int__

标签: python


【解决方案1】:

你的构造函数名称有错别字

def __int__(self, *args, **kwargs):
    self._changed = False
    self._name = ""
    self._description = ""

__int__ 更改为 __init__

def __init__(self, *args, **kwargs):
    self._changed = False
    self._name = ""
    self._description = ""

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-11
    • 1970-01-01
    • 2018-05-28
    • 2010-09-20
    相关资源
    最近更新 更多