您的位置:首页 > 编程语言 > Python开发

Python的repr和str有什么不同?

2011-04-27 14:14 579 查看
原文地址:
http://blog.csdn.net/XXKKFF/archive/2009/08/06/4420115.aspx
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.
view plaincopy to clipboardprint?

1. >>> try:

2. raise Exception(1,2,3);

3. except Exception as e:

4. print(e);

5. print(repr(e));

6. print(str(e));

7. print(e.args);

8.

9. (1, 2, 3)

10. Exception(1, 2, 3)

11. (1, 2, 3)

12. (1, 2, 3)

13. >>> s = 'hello world'

14. >>> str(s)

15. 'hello world'

16. >>> repr(s)

17. "'hello world'"

那么如何才能导入一个包 (它不过是磁盘上的一个目录) 并使其成为一个模块 (它总是在磁盘上的一个文件) 呢?答案就是神奇的 __init__.py
文件。你明白了吧,包不只是目录,它们是包含一个特殊文件 __init__.py
的目录。这个文件定义了包的属性和方法。例如,xml.dom
包含了 Node
类,它在xml/dom/__init__.py
中有所定义。当你将一个包作为模块导入 (比如从 xml
导入 dom
) 的时候,实际上导入了它的 __init__.py
文件。



一个包是一个其中带有特殊文件 __init__.py
的目录。__init__.py
文件定义了包的属性和方法。其实它可以什么也不定义;可以只是一个空文件,但是必须要存在。如果 __init__.py
不存在,这个目录就仅仅是一个目录,而不是一个包,它就不能被导入或者包含其它的模块和嵌套包。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: