Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python properties and string formatting

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)?

like image 960
Andrei Zbikowski Avatar asked Mar 11 '13 20:03

Andrei Zbikowski


2 Answers

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)

like image 155
mgilson Avatar answered Oct 13 '22 01:10

mgilson


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())
like image 45
askewchan Avatar answered Oct 13 '22 01:10

askewchan