python: 我可以在类的getter方法中使用字符串格式化操作符吗?
我想做类似这样的事情:
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__
但是这样不行,因为 name
和 count
是带有获取器的属性。
有没有办法解决这个问题,让我可以使用带有命名参数的格式字符串,从而调用这些获取器?
1 个回答
2
只需要把代码改成不使用 self.__dict__
。你得把 name
和 count
当作属性来访问,而不是试图用它们绑定的名字去访问:
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}
如果你重复一些东西或者有很多东西,这样可能会更好,但看起来有点奇怪。