擅长:python、mysql、java
<p>在您的示例中,您没有与字符串表示类型交互;而是与<code>int</code>表示类型交互。对象可以通过定义<code>__format__</code>方法来提供自己的格式化行为。如PEP 3101所述:</p>
<blockquote>
<pre><code>The new, global built-in function 'format' simply calls this special
method, similar to how len() and str() simply call their respective
special methods:
def format(value, format_spec):
return value.__format__(format_spec)
Several built-in types, including 'str', 'int', 'float', and 'object'
define __format__ methods. This means that if you derive from any of
those types, your class will know how to format itself.
</code></pre>
</blockquote>
<p>表示类型<code>s</code>不由<code>int</code>对象实现是可以理解的(请参阅每个对象类型的文档表示类型列表<a href="http://docs.python.org/3/library/string.html#format-specification-mini-language" rel="nofollow">here</a>)。异常消息有点误导人。如果没有<code>,</code>,问题就更清楚了:</p>
<pre><code>>>> format(10000, "s")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Unknown format code 's' for object of type 'int'
</code></pre>