Python 属性返回属性对象 [英] Python property returning property object

查看:48
本文介绍了Python 属性返回属性对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堂这样的课:

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>

我看过Python 属性是如何工作的?如何在__init__中设置python属性,但它们都是使用装饰器方法,我不这样做,因为我想要一个不同的名称.我需要访问 self

I've seen How do Python properties work?, How to set a python property in __init__, but they all use the decorator method, which i don't because i want a different name. And I need access to self

我如何让财产表现得正常?

How do i get the property to behave?

推荐答案

你需要做一个小改动:

class Foo(object):

    def get_bar(self):
        return "bar"

    bar = property(get_bar)

print Foo().bar # prints bar

属性需要是类的属性,而不是实例;这就是 descriptor 协议的工作原理.

The property needs to be an attribute of the class, not the instance; that's how the descriptor protocol works.

这篇关于Python 属性返回属性对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆