Python 属性返回属性对象

标签 python python-2.7

我有这样一个类:

class Foo(object):
    def __init__(self):
        self.bar = property(self.get_bar)

    def get_bar(self):
        return "bar"

print Foo().bar  #this prints <property object at 0x0051CB40>

我看过 How do Python properties work? , How to set a python property in __init__ ,但他们都使用装饰器方法,我不这样做,因为我想要一个不同的名称。我需要访问 self

我如何让属性正常运行?

最佳答案

你需要做一个小改动:

class Foo(object):

    def get_bar(self):
        return "bar"

    bar = property(get_bar)

print Foo().bar # prints bar

属性需要是类的属性,而不是实例; descriptor就是这样协议(protocol)有效。

关于Python 属性返回属性对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21812092/

相关文章:

python - 我如何重载\覆盖 Python 的断言语句以在断言通过时打印

python - 检查数字是否在两个数字内的更简洁的方法,如果不在则更改它

python - 在python中生成15分钟时间间隔数组

python - 当函数存储为字典值时调用函数

python - Openpyxl:确定单元格值中的哪个字符是删除线

python - 测试 : Allow Failure Rate

python - 解决 python 中的 lambda 限制

python - 如何实时处理图像并输出结果的实时视频?

python - Matplotlib B1-Motion(按住键的鼠标运动)等效?

python - 如何改进 Python 2.7 中文本文件中的写入流