Python属性与字符串格式化

5 投票
3 回答
4094 浏览
提问于 2025-04-17 18:43

我原以为在Python中用.format()来格式化字符串时,可以正确使用属性,但结果却是对象的默认字符串格式化方式:

>>> def get(): return "Blah"
>>> a = property(get)
>>> "{a}!".format(a=a)
'<property object at 0x221df18>!'

这是预期的行为吗?如果是的话,有什么好的方法可以让属性有特别的格式化行为呢?比如,上面的测试应该返回“Blah!”而不是其他的。

3 个回答

1

是的,这基本上和你直接写:

>>> def get(): return "Blah"
>>> a = property(get)
>>> print a

如果你想要 "Blah",只需要调用这个函数:

>>> def get(): return "Blah"
>>> a = property(get)
>>> "{a}!".format(a=a.fget())
1

Python中的属性可以很好地与.format()一起使用。看看下面这个例子:

>>> class Example(object):
...     def __init__(self):
...             self._x = 'Blah'
...     def getx(self): return self._x
...     def setx(self, value): self._x = value
...     def delx(self): del self._x
...     x = property(getx,setx,delx, "I'm the 'x' property.")
...
>>>
>>> ex = Example()
>>> ex.x
'Blah'
>>> print(ex.x)
'Blah'
>>> "{x.x}!".format(x=ex)
'Blah!'

我觉得你的问题可能是因为你的属性没有放在一个类里面。你是怎么使用这些属性的,为什么它们在.format()中不工作呢?

9

property 对象是描述符。简单来说,它们本身没有什么特别的功能,只有通过一个类才能使用。

像下面这样:

class Foo(object):
     @property
     def blah(self):
         return "Cheddar Cheese!"

a = Foo()
print('{a.blah}'.format(a=a))

应该可以正常工作。(你会看到 Cheddar Cheese! 被打印出来)

撰写回答