【http://blog.youkuaiyun.com/followingturing/article/details/7954204】
__str__ 直接打印对象的实现方法
在python语言里,__str__一般是格式是这样的。
class A:
def __str__(self):
return "this is in str"
事实上,__str__是被print函数调用的,一般都是return一个什么东西。这个东西应该是以字符串的形式表现的。如果不是要用str()函数转换。当你打印一个类的时候,那么print首先调用的就是类里面的定义的__str__,比如:str.py
#!/usr/bin/env python
class strtest:
def __init__(self):
print "init: this is only test"
def __str__(self):
return "str: this is only test"
if __name__ == "__main__":
st=strtest()
print st
$./str.py
init: this is only test
str: this is only test
从上面例子可以看出,当打印strtest的一个实例st的时候,__str__函数被调用到。
其实,python里面的对象基本上都默认有个__str__供print函数所用。比如字典里的__str__,见红色部分:
>>> dir({})
['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values', 'viewitems', 'viewkeys', 'viewvalues']
>>> t={}
>>> t['1'] = "hello"
>>> t['2'] = "world"
>>> t
{'1': 'hello', '2': 'world'}
>>> print t
{'1': 'hello', '2': 'world'}
>>> t.__str__()
"{'1': 'hello', '2': 'world'}"
>>>
大家可以看到一个字典,print t 和 t.__str__()是一样的。只不过__str__()将字典内容以字符串形式输出。
看看下面的例子,如果在函数__str__里返回的不是字符串,请看str1.py
#!/us/bin/env/python
#__metaclass__ = type
#if __name__ == "__main__":
class strtest:
def __init__(self):
self.val = 1
def __str__(self):
return self.val
if __name__ == "__main__":
st=strtest()
print st
$./str1.py
Traceback (most recent call last):
File "./str.py", line 12, in <module>
print st
TypeError: __str__ returned non-string (type int)
错误的信息提示:__str__返回了一个非字符串。这时候我们应该这样做:请看str2.py
#!/usr/bin/env python
#__metaclass__ = type
#if __name__ == "__main__":
class strtest:
def __init__(self):
self.val = 1
def __str__(self):
return str(self.val)
if __name__ == "__main__":
st=strtest()
print st
$./str2.py
1
我们用str()将整型变为了字符型。
【http://maxomnis.iteye.com/blog/1911208】
Python 有办法将任意值转为字符串:将它传入repr() 或str() 函数。
函数str() 用于将值转化为适于人阅读的形式,而repr() 转化为供解释器读取的形式
(如果没有等价的语法,则会发生SyntaxError 异常) 某对象没有适于人阅读的解释形式的话, str() 会返回与repr()等同的值。很多类型,诸如数值或链表、字典这样的结构,针对各函数都有着统一的解读方式。
字符串和浮点数,有着独特的解读方式。
>>> class Person(object):
def __str__(self):
return "in__str__"
def __repr__(self):
return "in_repr__"
>>> p = Person()
>>> p
in_repr__
>>> str(p)
'in__str__'
>>> repr(p)
'in_repr__'
>>> print repr(p)
in_repr__
>>> print p
in__str__
p跟print repr(p)和print p一致。
str()一般是将数值转成字符串。
repr()是将一个对象转成字符串显示,注意只是显示用,有些对象转成字符串没有直接的意思。如list,dict使用str()是无效的,但使用repr可以,这是为了看它们都有哪些值,为了显示之用。
The str() function is meant to return representations of values which are fairly
human-readable, while repr() is meant to generate representations which can be read by
the interpreter (or will force a SyntaxError if there is not equivalent syntax). For
objects which don't have a particular representation for human consumption, str() will
return the same value as repr(). Many values, such as numbers or structures like lists
and dictionaries, have the same representation using either function. Strings and
floating point numbers, in particular, have two distinct representations.
>>> s = "Hello, world."
>>> str(s)
'Hello, world.'
>>> repr(s)
"'Hello, world.'"
>>> str(0.1)
'0.1'
>>> repr(0.1)
'0.1'
>>> x = 10 * 3.25
>>> y = 200 * 200
>>> s = 'The value of x is '+ repr(x) + ', and y is ' + repr(y) + '...'
>>> print s
The value of x is 32.5, and y is 40000...
>>> hello = 'hello, world\n'
>>> hellos = repr(hello)
>>> print hellos
'hello, world\n'
>>> hellos
"'hello, world\\n'"
>>>