Python属性和字符串格式

And*_*ski 3 python string formatting properties

我在印象python字符串格式使用.format()将正确使用属性,而我得到一个字符串格式的对象的默认行为:

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

这是预期的行为,如果是的话,什么是实现属性的特殊行为的好方法(例如,上面的测试将返回"Blah!"而不是)?

mgi*_*son 7

property对象是描述符.因此,除非通过课程访问,否则他们没有任何特殊能力.

就像是:

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

a = Foo()
print('{a.blah}'.format(a=a))
Run Code Online (Sandbox Code Playgroud)

应该管用.(你会看到Cheddar Cheese!印刷)