Python中str()与__str__、repr()与__repr__、eval()、__unicode__的关系与区别

时间:2022-04-29 13:25:26

Python中str()与__str__、repr()与__repr__、eval()、__unicode__的关系与区别

首先

先弄清楚str()与__str__、repr()与__repr__ 的区别,str()与repr()都是python中的内置函数,是直接用来格式化字符串的函数。而__str__与__repr__ 是在类(对象)中对类(对象)本身进行字符串处理。

其次

需要弄清楚str与repr之间的区别【引用】

python3

>>> help(str)
Help on class str in module builtins:

class str(object)
| str(object='') -> str
| str(bytes_or_buffer[, encoding[, errors]]) -> str
|
| Create a new string object from the given object. If encoding or
| errors is specified, then the object must expose a data buffer
| that will be decoded using the given encoding and error handler.
| Otherwise, returns the result of object.__str__() (if defined)
| or repr(object).
| encoding defaults to sys.getdefaultencoding().
| errors defaults to 'strict'.

python2

class str(basestring)
| str(object='') -> string
|
| Return a nice string representation of the object.
| If the argument is a string, the return value is the same object.

str【引用】

返回一个可以用来表示对象的可打印的友好的字符串

对字符串,返回本身。
没有参数,则返回空字符串
对类,可通过__str__() 成员控制其行为。该成员不存在,则使用其 __repr__() 成员。

与 repr 区别:不总是尝试生成一个传给 eval 的字符串,其目标是可打印字符串。

python3

>>> help(repr)
Help on built-in function repr in module builtins:

repr(obj, /)
Return the canonical string representation of the object.

For many object types, including most builtins, eval(repr(obj)) == obj.

python2

repr(...)
repr(object) -> string

Return the canonical string representation of the object.
For most object types, eval(repr(object)) == object.

repr【引用】

返回一个可以用来表示对象的可打印字符串

首先,尝试生成这样一个字符串,将其传给 eval()可重新生成同样的对象
否则,生成用尖括号包住的字符串,包含类型名和额外的信息(比如地址)
一个类(class)可以通过 __repr__() 成员来控制repr()函数作用在其实例上时的行为。

class a():
def __unicode__(self):
pass

def __str__(self):
pass

def __repr__(self):
pass
>>> help(eval)
Help on built-in function eval in module builtins:

eval(source, globals=None, locals=None, /)
Evaluate the given source in the context of globals and locals.

The source may be a string representing a Python expression
or a code object as returned by compile().
The globals must be a dictionary and locals can be any mapping,
defaulting to the current globals and locals.
If only globals is given, locals defaults to it.
>>> eval('1+2')
3
>>> str('1+2')
'1+2'
>>> repr('1+2')
"'1+2'"
>>> type(repr('1+2'))
<class 'str'>
>>> type(str('1+2'))
<class 'str'>
>>> type(eval('1+2'))
<class 'int'>
#就相当于上面说的eval(repr(object)) == object
>>> eval(repr('1+2'))
'1+2'
>>> '1+2'
'1+2'

示例

#test2.py
class A(object):
def __str__(self):
return "__str__"
def __repr__(self):
return "__repr__"

a = A()
b = A
>>> import test2
>>> test2.a
__repr__
>>> print(test2.a)
__str__
>>> test2.b
<class 'test2.A'>
>>> print(test2.b)
<class 'test2.A'>