python:我可以使用类的getter方法使用字符串格式化运算符吗?

时间:2011-07-15 15:07:15

标签: python class dictionary format properties

我想做这样的事情:

class Foo(object):
    def __init__(self, name):
        self._name = name
        self._count = 0
    def getName(self):
        return self._name
    name = property(getName)
    def getCount(self):
        c = self._count
        self._count += 1
        return c
    count = property(getCount)
    def __repr__(self):
        return "Foo %(name)s count=%(count)d" % self.__dict__

但这不起作用,因为namecount是带有getter的属性。

有没有办法解决这个问题,所以我可以使用带有命名参数的格式字符串来调用getter?

1 个答案:

答案 0 :(得分:2)

只需将其更改为不使用self.__dict__即可。您必须访问namecount作为属性,而不是尝试通过其属性绑定的名称来访问它们:

class Foo(object):
    def __init__(self, name):
        self._name = name
        self._count = 0
    def getName(self):
        return self._name
    name = property(getName)
    def getCount(self):
        c = self._count
        self._count += 1
        return c
    count = property(getCount)
    def __repr__(self):
        return "Foo %s count=%d" % (self.name, self.count)

然后在使用中:

>>> f = Foo("name")
>>> repr(f)
'Foo name count=0'
>>> repr(f)
'Foo name count=1'
>>> repr(f)
'Foo name count=2'

编辑:您仍然可以使用命名格式,但您必须更改方法,因为您无法通过所需的名称访问属性:

def __repr__(self):
    return "Foo %(name)s count=%(count)d" % {'name': self.name, 'count': self.count}

如果你重复一些事情和/或有很多事情,这个可以更好,但它有点傻。