Python的repr和str有什么不同?

 

原文地址:

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 不存在,这个目录就仅仅是一个目录,而不是一个包,它就不能被导入或者包含其它的模块和嵌套包。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值