Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1757204
  • 博文数量: 335
  • 博客积分: 4690
  • 博客等级: 上校
  • 技术积分: 4341
  • 用 户 组: 普通用户
  • 注册时间: 2010-05-08 21:38
个人简介

无聊之人--除了技术,还是技术,你懂得

文章分类

全部博文(335)

文章存档

2016年(29)

2015年(18)

2014年(7)

2013年(86)

2012年(90)

2011年(105)

分类: Python/Ruby

2011-06-15 23:20:13

4.3. Using typestrdir, and Other Built-In Functions

Type,str,dir等其他内置函数的使用

Python has a small set of extremely useful built-in functions. All other functions are partitioned off into modules. This was actually a conscious design decision, to keep the core language from getting bloated like other scripting languages (cough cough, Visual Basic).

Python含有一批非常有用的内置函数的集合。剩余其它的函数都被分到了其他模块中。这是实际潜意识设计决定,为了保持核心语言免得变得过于膨胀,如同其它语言(哎,如VB

4.3.1. The type Function

Type函数

The type function returns the datatype of any arbitrary object. The possible types are listed in the types module. This is useful for helper functions that can handle several types of data.

Type 返回任意对象的数据类型。所有可能的类型都在type模块中。对于那些要处理几种类型数据的帮助函数是非常有用的。

Example 4.5. Introducing type

4.5 type 介绍

  1. >>> type(1)
  2. <type 'int'>
  3. >>> li = []
  4. >>> type(li)
  5. <type 'list'>
  6. >>> import odbchelper
  7. >>> type(odbchelper)
  8. <type 'module'>
  9. >>> import types
  10. >>> type(odbchelper) == types.ModuleType
  11. True

1

type takes anything -- and I mean anything -- and returns its datatype. Integers, strings, lists, dictionaries, tuples, functions, classes, modules, even types are acceptable.

Type可以接受任何对象,--我的意思是任何对象然后返回该对象的数据类型。整数,字符串,列表,字典,tuple,函数,类,模块,甚至types 本身都是可以接受的

2

type can take a variable and return its datatype.

Type 接受一个变量做参数,然后返回该变量的数据类型

3

type also works on modules.

Type 同样使用于 module

4

You can use the constants in the types module to compare types of objects. This is what the info function does, as you'll see shortly.

Type 模块可以接受常量来比较不同的对象。正如稍后你将看到的,这正是info函数所做的。

4.3.2. The str Function

Str 函数

The str coerces data into a string. Every datatype can be coerced into a string.

Str强制转换数据为字符串类型。所有的数据类型都可以强制转换成字符串类型。

Example 4.6. Introducing str

4.6 str简介

  1. >>> str(1)
  2. '1'
  3. >>> horsemen = ['war', 'pestilence', 'famine']
  4. >>> horsemen
  5. ['war', 'pestilence', 'famine']
  6. >>> horsemen.append('Powerbuilder')
  7. >>> str(horsemen)
  8. "['war', 'pestilence', 'famine', 'Powerbuilder']"
  9. >>> str(odbchelper)
  10. ""
  11. >>> str(None)
  12. 'None'

1

For simple datatypes like integers, you would expect str to work, because almost every language has a function to convert an integer to a string.

对于简单的数据类型如整型,你期望str能起作用,这是因为每一种语言都存在一个函数可以将一个整数转换成字符串

2

However, str works on any object of any type. Here it works on a list which you've constructed in bits and pieces.

但是str适用于任意数据类型的对象。这个它接受一个list作为参数,这个列表通过零碎的对象构建起来。

3

str also works on modules. Note that the string representation of the module includes the pathname of the module on disk, so yours will be different.

Str 同样适用于模块。值得注意的是模块的字符包含了模块在硬盘上的路径上,你的可能会和上面的结果不同。

4

A subtle but important behavior of str is that it works on None, the Python null value. It returns the string 'None'. You'll use this to your advantage in the info function, as you'll see shortly.

这是str很微小但是很重要的一种特性,当它的参数是None时,Python的空值。它返回字符串’None’.正如稍后你将看到,你将利用这点来体现函数info的优势。

At the heart of the info function is the powerful dir function. dir returns a list of the attributes and methods of any object: modules, functions, strings, lists, dictionaries... pretty much anything.

Info函数的核心是功能强大的dir函数。Dir函数返回的是任意对象的方法和属性所组成的列表:对象包括:模块,函数,字符串,列表,字典等尽可能多的对象。

Example 4.7. Introducing dir

4.7 dir函数简介

  1. >>> li = []
  2. >>> dir(li)
  3. ['append', 'count', 'extend', 'index', 'insert',
  4. 'pop', 'remove', 'reverse', 'sort']
  5. >>> d = {}
  6. >>> dir(d)
  7. ['clear', 'copy', 'get', 'has_key', 'items', 'keys', 'setdefault', 'update', 'values']
  8. >>> import odbchelper
  9. >>> dir(odbchelper)
  10. ['__builtins__', '__doc__', '__file__', '__name__', 'buildConnectionString']

1

li is a list, so dir(li) returns a list of all the methods of a list. Note that the returned list contains the names of the methods as strings, not the methods themselves

Li 是一个列表,因此dir(li)返回的是列表的方法列表。值得注意的是,返回的列表包含的是方法名字的字符串形式,而不是方法本身。.

2

d is a dictionary, so dir(d) returns a list of the names of dictionary methods. At least one of these, keys, should look familiar.

D是一个字典,因此,dir(d)返回的是字典方法的名字所组成的列表。在这些方法中key方法肯定看起来面熟。

3

This is where it really gets interesting. odbchelper is a module, so dir(odbchelper) returns a list of all kinds of stuff defined in the module, including built-in attributes, like __name____doc__, and whatever other attributes and methods you define. In this case, odbchelper has only one user-defined method, the buildConnectionStringfunction described in Chapter 2.

这真是dir函数真正有趣的所在。Odbchelper是一个模块,因此dir(odbchelper)返回的是模块定义时所有的东四所组成的列表,包括内置属性如__name__,__doc__,以及其他你定义的属性和方法。在本例中,odbchelper只包含一个用户自定义的方法,也就是在第二章介绍的buildConnectonString.

Finally, the callable function takes any object and returns True if the object can be called, or False otherwise. Callable objects include functions, class methods, even classes themselves. (More on classes in the next chapter.)

最后,callable函数接受任意参数,如果该对象是可被调用的,则返回真值,否则返回假。可调用的对象包括函数,类方法,甚至方法本身(关于方法的更多内容将在下一章介绍。

Example 4.8. Introducing callable

4.8 callable 简介

  1. >>> import string
  2. >>> string.punctuation
  3. '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
  4. >>> string.join
  5. <function join at 00C55A7C>
  6. >>> callable(string.punctuation)
  7. False
  8. >>> callable(string.join)
  9. True
  10. >>> print string.join.__doc__
  11. join(list [,sep]) -> string
  12.  
  13.     Return a string composed of the words in list, with
  14.     intervening occurrences of sep. The default separator is a
  15.     single space.
  16.  
  17.     (joinfields and join are synonymous)

1

The functions in the string module are deprecated (although many people still use the join function), but the module contains a lot of useful constants like thisstring.punctuation, which contains all the standard punctuation characters.

String模块中的方法是不被提倡(虽然任然有很多人使用join方法。但是这个模块拥有了许多有用的常量如这个string.punctuation,它包哈了所有标准的punctilious字符(类似分隔符)

2

string.join is a function that joins a list of strings.

String.join 是一个函数,将列表中的字符串连接起来。

3

string.punctuation is not callable; it is a string. (A string does have callable methods, but the string itself is not callable.)

strin.punctuation 不是可调用的,它只是一个字符串。(一个字符串可以拥有可调用的方法,但是字符串本身确实不可调用的)

4

string.join is callable; it's a function that takes two arguments.

String.join是可以被调用的,该函数拥有连个参数。

5

Any callable object may have a doc string. By using the callable function on each of an object's attributes, you can determine which attributes you care about (methods, functions, classes) and which you want to ignore (constants and so on) without knowing anything about the object ahead of time.

一个可调用的对象可能会有文档化的字符串。通过对一个对象的所有属性应用callable函数,不需要提前了解该对象,你就能确定你所关心的属性(方法,函数,类)以及你想忽略的属性(常量等)。

4.3.3. Built-In Functions

内置函数

typestrdir, and all the rest of Python's built-in functions are grouped into a special module called __builtin__. (That's two underscores before and after.) If it helps, you can think of Python automatically executing from __builtin__ import * on startup, which imports all the “built-in” functions into the namespace so you can use them directly.

Type,strdir以及其它剩余的Python内置函数都被归类为一个特殊的模块---__buildin__。(注意在buildin前后都有两个下划线。)如果它有用,你可以认为Python解释器在刚开始启动的时候就自动执行 from __buildin__ import  *,它会导入所有的内置函数到命名空间,这样你就可以直接使用。

The advantage of thinking like this is that you can access all the built-in functions and attributes as a group by getting information about the __builtin__ module. And guess what, Python has a function called info. Try it yourself and skim through the list now. We'll dive into some of the more important functions later. (Some of the built-in error classes, like AttributeError, should already look familiar.)

上述想法的好处是你可以使用这些内置函数和属性,可以通过__buildin__来获取相关信息并将他们归为一类。这样你就猜出Python为什么有这个函数info.自己尝试一下并跳过下面的内容。我们稍后将深入研究一些更重要的函数(一些内置的错误类,如AttributeError,看起来已经很熟悉了。

Example 4.9. Built-in Attributes and Functions

4.9 内置属性和函数

  1. >>> from apihelper import info
  2. >>> import __builtin__
  3. >>> info(__builtin__, 20)
  4. ArithmeticError Base class for arithmetic errors.
  5. AssertionError Assertion failed.
  6. AttributeError Attribute not found.
  7. EOFError Read beyond end of file.
  8. EnvironmentError Base class for I/O related errors.
  9. Exception Common base class for all exceptions.
  10. FloatingPointError Floating point operation failed.
  11. IOError I/O operation failed.
  12.  
  13. [...snip...]

Note

 

Python comes with excellent reference manuals, which you should peruse thoroughly to learn all the modules Python has to offer. But unlike most languages, where you would find yourself referring back to the manuals or man pages to remind yourself how to use these modules, Python is largely self-documenting.

Python拥有良好的引用手册,你应该完全的熟读精研Python所提供必须的模块。但是不同于其它大多数语言,在其它语言中你可能经常查看哪些手册或是帮助文档以防止忘记模块的使用方法,Python在很大程度是自说明的。

 

 

阅读(1026) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~