为什么在打印向量时隐式调用 str(vector)?
Why when printing a vector is str(vector) implicitly called?
本段以下的所有内容均来自《实用 Maya 编程》一书。在倒数第二行中,作者说带有参数 t
的 print
语句隐式调用 str(t)
,我想知道为什么,同样在作者创建的第二个代码块中vect
赋值给xform.translate.get()
,他不就继续用t
也赋给了xform.translate.get()
吗?
>>> xform.translate
Attribute(u'pSphere1.translate')
>>> t = xform.translate.get()
>>> print t
[0.0, 0.0, 0.0]
突出显示的球体变换的平移值似乎是一个列表。它不是。翻译值是 pymel.core.datatypes.Vector 的实例。有时我们需要更积极地内省对象。我认为这是 PyMEL 犯错误的少数领域之一。调用 str(t) returns 一个看起来像来自列表的字符串,而不是看起来像来自 Vector 的字符串。确保你有正确的类型。我花了几个小时来寻找我使用 Vector 而不是列表的错误,反之亦然。
>>> vect = xform.translate.get()
>>> lst = [0.0, 0.0, 0.0]
>>> str(vect)
'[0.0, 0.0, 0.0]'
>>> str(lst)
'[0.0, 0.0, 0.0]'
>>> print t, lst # The print implicitly calls str(t)
[0.0, 0.0, 0.0] [0.0, 0.0, 0.0]
那是因为 Python 的数据模型。根据 docs:
object.__str__(self)
Called by str(object)
and the built-in functions
format()
and print()
to compute the “informal” or nicely printable
string representation of an object. The return value must be a string
object.
This method differs from object.__repr__()
in that there is no
expectation that __str__()
return a valid Python expression: a more
convenient or concise representation can be used.
The default implementation defined by the built-in type object calls
object.__repr__()
.
如您所见,Python 的 print(object)
在内部调用 object.__str__()
,其中 returns 对象的字符串表示形式。调用 str(object)
也 returns object.__str__()
.
因此,print(object)
和 str(object)
都会为您提供相同的视觉输出。
本段以下的所有内容均来自《实用 Maya 编程》一书。在倒数第二行中,作者说带有参数 t
的 print
语句隐式调用 str(t)
,我想知道为什么,同样在作者创建的第二个代码块中vect
赋值给xform.translate.get()
,他不就继续用t
也赋给了xform.translate.get()
吗?
>>> xform.translate
Attribute(u'pSphere1.translate')
>>> t = xform.translate.get()
>>> print t
[0.0, 0.0, 0.0]
突出显示的球体变换的平移值似乎是一个列表。它不是。翻译值是 pymel.core.datatypes.Vector 的实例。有时我们需要更积极地内省对象。我认为这是 PyMEL 犯错误的少数领域之一。调用 str(t) returns 一个看起来像来自列表的字符串,而不是看起来像来自 Vector 的字符串。确保你有正确的类型。我花了几个小时来寻找我使用 Vector 而不是列表的错误,反之亦然。
>>> vect = xform.translate.get()
>>> lst = [0.0, 0.0, 0.0]
>>> str(vect)
'[0.0, 0.0, 0.0]'
>>> str(lst)
'[0.0, 0.0, 0.0]'
>>> print t, lst # The print implicitly calls str(t)
[0.0, 0.0, 0.0] [0.0, 0.0, 0.0]
那是因为 Python 的数据模型。根据 docs:
object.__str__(self)
Called bystr(object)
and the built-in functionsformat()
andprint()
to compute the “informal” or nicely printable string representation of an object. The return value must be a string object.This method differs from
object.__repr__()
in that there is no expectation that__str__()
return a valid Python expression: a more convenient or concise representation can be used.The default implementation defined by the built-in type object calls
object.__repr__()
.
如您所见,Python 的 print(object)
在内部调用 object.__str__()
,其中 returns 对象的字符串表示形式。调用 str(object)
也 returns object.__str__()
.
因此,print(object)
和 str(object)
都会为您提供相同的视觉输出。