开发者

python: can I use a string formatting operator with a class's getter methods?

I want to do something like this:

class Foo(object):
    def __init__(self, name):
        self._name = name
        self._co开发者_高级运维unt = 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__

but that doesn't work because name and count are properties with getters.

Is there a way to fix this so I can use a format string with named arguments to cause getters to be called?


Just change it to not use self.__dict__. You have to access name and count as properties instead of trying to access them by the names that their properties are bound to:

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)

Then in use:

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

EDIT: You can still use named formatting but you have to change your approach since you can't access the properties via the names you want:

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

This could be better if you repeat things and/or have a lot of things, but it is a bit goofy.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜