Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python属性和字符串格式_Python_String_Properties_Formatting - Fatal编程技术网

Python属性和字符串格式

Python属性和字符串格式,python,string,properties,formatting,Python,String,Properties,Formatting,我的印象是,使用.format()进行python字符串格式化将正确使用属性,而我得到的是字符串格式化对象的默认行为: >>> def get(): return "Blah" >>> a = property(get) >>> "{a}!".format(a=a) '<property object at 0x221df18>!' >def get():返回“Blah” >>>a=属性(get) >>>“{a}!”格式(a=a

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

>>> def get(): return "Blah"
>>> a = property(get)
>>> "{a}!".format(a=a)
'<property object at 0x221df18>!'
>def get():返回“Blah”
>>>a=属性(get)
>>>“{a}!”格式(a=a)
'!'

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

是的,这与您刚才做的基本相同:

>>> def get(): return "Blah"
>>> a = property(get)
>>> print a
如果您想要
“Blah”
只需调用以下函数:

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

属性
对象是描述符。因此,除非通过类访问,否则它们没有任何特殊能力

比如:

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

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

应该有用。(您将看到
切达奶酪!
打印)

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

这就是我感到困惑的地方,在类中使用property()而不是属性装饰器。谢谢还要注意,只能在实例上访问属性。请参见此处:注意此处
格式
未调用您的属性。Python正在调用您的属性来解析要传递给
格式的对象。这只是吹毛求疵,但它与
'{x.x}.format(x=ex)
略有不同,在
format
函数/方法中调用属性的getter。