I was under the impression python string formatting using .format() would correctly use properties, instead I get the default behaviour of an object being string-formatted:
>>> def get(): return "Blah"
>>> a = property(get)
>>> "{a}!".format(a=a)
'<property object at 0x221df18>!'
Is this the intended behaviour, and if so what's a good way to implement a special behaviour for properties (eg, the above test would return "Blah!" instead)?
property
objects are descriptors. As such, they don't have any special abilities unless accessed through a class.
something like:
class Foo(object):
@property
def blah(self):
return "Cheddar Cheese!"
a = Foo()
print('{a.blah}'.format(a=a))
should work. (You'll see Cheddar Cheese!
printed)
Yes, this is basically the same as if you just did:
>>> def get(): return "Blah"
>>> a = property(get)
>>> print a
If you want "Blah"
just call the function:
>>> def get(): return "Blah"
>>> a = property(get)
>>> "{a}!".format(a=a.fget())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With