python __format__ 方法应该如何用于 int?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2179926/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How is the __format__ method supposed to be used for int?
提问by Juanjo Conti
I saw there was a __format__
method but help(int.__format__
) doesn't provide any help.
我看到有一种__format__
方法,但 help( int.__format__
) 没有提供任何帮助。
I also know you're not suppose to call a __method__
directly. When is this method called? Which is its argument?
我也知道你不应该__method__
直接打电话给 a 。这个方法什么时候调用?它的论据是什么?
采纳答案by Steven Kryskalla
It's used for Py3k's new string formatting scheme.
它用于 Py3k 的新字符串格式化方案。
You can find more info here:
您可以在此处找到更多信息:
http://docs.python.org/whatsnew/2.6.html#pep-3101-advanced-string-formatting
http://docs.python.org/whatsnew/2.6.html#pep-3101-advanced-string-formatting
You are right that it isn't called directly. It's called by str.format
or the new format
builtin.
你是对的,它没有被直接调用。它由str.format
或 新format
内置函数调用。
回答by Tor Valamo
It's used when you pass an integer to the format() function. The details elude me, as I can't seem to get it to tell me what exactly the argument is. (Edit: see lost-theory's link)
当您将整数传递给 format() 函数时会使用它。细节让我望而却步,因为我似乎无法让它告诉我争论的确切内容。(编辑:见丢失理论的链接)
Oh, and it only works when the integer is the only argument. If you pass a tuple to format, then the tuple.__format__ function is called, and the int.__str__ or something.
哦,它仅在整数是唯一参数时才有效。如果你传递一个元组来格式化,那么 tuple.__format__ 函数就会被调用,还有 int.__str__ 或其他东西。
'{0}'.format(4)
str(4.__format__(format_spec=''))