【问题标题】:python: can I use a string formatting operator with a class's getter methods?python:我可以将字符串格式化运算符与类的 getter 方法一起使用吗?
【发布时间】:2011-10-06 06:03:06
【问题描述】:

我想做这样的事情:

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?

【问题讨论】:

    标签: python class dictionary format properties


    【解决方案1】:

    只需将其更改为不使用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}
    

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

    【讨论】:

    • 我知道我可以做到,但我宁愿在格式化字符串中使用命名参数。我有一个案例,其中有 6 个或 7 个字段而不是 2 个,并且保持列表和格式字符串同步会令人困惑。
    • @Jason 是的,不幸的是,没有很好的方法可以做到这一点,如果您想通过名称namecount 访问属性,则必须以这种方式访问​​属性。我添加了一种愚蠢的方式,您可以使用仍然使用名称格式,它可能更适合您的需求,但可能不会。
    • +1:这有点蛮力(或者你说的“愚蠢”),但非常简单。谢谢!
    • 更好的方法可能是使用 dict 构造函数和关键字来定义它。至少这样你就不用打那么多引号了! ... % dict(name=self.name, count=self.count)
    猜你喜欢
    • 1970-01-01
    • 2011-11-25
    • 2012-05-18
    • 2020-06-13
    • 1970-01-01
    • 2019-05-26
    • 2018-04-17
    • 2021-10-06
    • 1970-01-01
    相关资源
    最近更新 更多