2006年03月17日

在字符和数字间相互转换
Problem
You need to turn a character into its numeric ASCII (ISO) or Unicode code, and vice versa.
将字符转换成ASCII码或者Unicode码

Solution
That’s what the built-in functions ord and chr are for:
内置的ord或者chr方法:

>>> print ord(‘a’)
97
>>> print chr(97)
a
The built-in function ord also accepts as its argument a Unicode string of length one, in which case it returns a Unicode code value, up to 65536. To make a Unicode string of length one from a numeric Unicode code value, use the built-in function unichr:

>>> print ord(u’\u2020′)
8224
>>> print repr(unichr(8224))
u’\u2020′


Discussion
It’s a mundane task, to be sure, but it is sometimes useful to turn a character (which in Python just means a string of length one) into its ASCII or Unicode code, and vice versa. The built-in functions ord, chr, and unichr cover all the related needs. Note, in particular, the huge difference between chr(n) and str(n), which beginners sometimes confuse…:

>>> print repr(chr(97))
‘a’
>>> print repr(str(97))
‘97′

请注意str和chr的区别:
chr用0-255的整形作为参数,返回相应的按照ASCII码对应出来的单字节字符串,str用任何整型作为参数,返回的则是该数字相应的字符串格式。
chr takes as its argument a small integer and returns the corresponding single-character string according to ASCII, while str, called with any integer, returns the string that is the decimal representation of that integer.

To turn a string into a list of character value codes, use the built-in functions map and ord together, as follows:

>>> print map(ord, ‘ciao’)
[99, 105, 97, 111]


To build a string from a list of character codes, use ”.join, map and chr; for example:

>>> print ”.join(map(chr, range(97, 100)))
abc


See Also
Documentation for the built-in functions chr, ord, and unichr in the Library Reference and Python in a Nutshell.

每次处理特定字符串的一个字节

问题:
你想每次只处理一个字符串的一个字节

解决办法:
你可以创建一个list,其内在的项目是字符串的字母。调用list,将字符串作为其参数
thelist = list(thestring)
你不必创建这个list,因为你可以直接用for语句
for character in thestring:
    do_something_with(c)
或者用直接使用以下的语句,将for循环放在其中:
results = [do_something_with(c) for c in thestring]
或者,同以上语句一样作用,调用map函数遍历字符串的每个字节:
results = map(do_something, thestring)

讨论
在python中,字节就是长度为1的字符串。可以通过遍历整个字符串来得到每一个字节。也可以通过map函数来达到同样的目的,只要需要对character进行的操作是一个函数就行。最后,你也可以调用内置类型list来获取一个string的长度为1的子字符串(比如string的单个字母)。如果你希望其元素是string的字母的set集合(2.4版),你也可以调用sets.Set,string作为其参数
import sets
magic_chars = sets.Set(‘abracadabra’)
poppins_chars = sets.Set(’supercalifragilisticexpialidocious’)
print ”.join(magic_chars & poppins_chars)   # set intersection
acrd


See Also
The Library Reference section on sequences; Perl Cookbook Recipe 1.5.

2006年03月16日

Python.Visual.QuickStart.Guide.chm
Wrox.Beginning.Python.Jul.2005.eBook-LinG.pdf
还有很多其它的书籍,我就不一一介绍了,其它的书籍在很多的网站上都可以找到,比较经典的,比如深入python,python cookbook,python core programming等。
如果各位有需要,可以联系我。

我的联系方式:
email:oneclubw@gmail.com
qq      :328250402
g-talk :oneclubw@gmail.com
msn   :oneclubw@hotmail.com

欢迎大家交流学习python的方法和经验。

2006年02月15日

首先注明:以下几个部分都是讲述关于内置对象的问题,一个观点:

python中一切皆是对象(Object)

2.1 Built-in Functions

The Python interpreter has a number of functions built into it that are
always available. They are listed here in alphabetical order.

__import__( name[, globals[,
locals
[,
fromlist
]]])
This function is invoked by the import statement. It mainly exists so that you can replace it with
another function that has a compatible interface, in order to change the
semantics of the import statement. For examples of why
and how you would do this, see the standard library modules ihooks and rexec. See also the built-in module imp, which
defines some useful operations out of which you can build your own __import__() function.

For example, the statement "import spam" results in the
following call: __import__('spam', globals(),
locals(), []); the statement "from spam.ham import
eggs
" results in "__import__('spam.ham', globals(),
locals(), ['eggs'])
". Note that even though locals() and
['eggs'] are passed in as arguments, the __import__() function does not set the local variable named
eggs; this is done by subsequent code that is generated for the
import statement. (In fact, the standard implementation does not use its
locals argument at all, and uses its globals only to
determine the package context of the import statement.)

When the name variable is of the form package.module,
normally, the top-level package (the name up till the first dot) is returned,
not the module named by name. However, when a non-empty
fromlist argument is given, the module named by name is
returned. This is done for compatibility with the bytecode generated for the
different kinds of import statement; when using "import
spam.ham.eggs
", the top-level package spam must be
placed in the importing namespace, but when using "from spam.ham
import eggs
", the spam.ham subpackage must be used to find the
eggs variable. As a workaround for this behavior, use getattr() to extract the desired components. For example,
you could define the following helper:

def my_import(name):
mod = __import__(name)
components = name.split('.')
for comp in components[1:]:
mod = getattr(mod, comp)
return mod
abs( x)
Return the absolute value of a number. The argument may be a plain or long
integer or a floating point number. If the argument is a complex number, its
magnitude is returned.
该函数返回一个number的绝对值。参数x可以是plain、long interger或者浮点。如果参数是复数,返回其数量级。
basestring( )
This abstract type is the superclass for str and unicode. It cannot be called or instantiated, but it can be
used to test whether an object is an instance of str or unicode. isinstance(obj, basestring) is equivalent
to isinstance(obj, (str, unicode)). New in
version 2.3.
这种抽象类型是str或者unicode类型的父类。它本身不能被调用或者实例化,但是可以用以测试一个对象到底是不是str或者unicode类型。isinstance(obj,basestring)等同isinstance(obj,(str,unicode))。
bool( [x])
Convert a value to a Boolean, using the standard truth testing procedure. If
x is false or omitted, this returns False;
otherwise it returns True. bool is
also a class, which is a subclass of int. Class bool cannot be subclassed further. Its only instances are False and True.

New in version
2.2.1.
Changed in version 2.3: If no argument is
given, this function returns False.

将一个值转化为布尔类型。如果x值假或者省略没有,返回False;反之返回True。bool也是一个类,是int的父类。bool类没有其他的父类呢。它只可能被实例化为False或者True。
python2.2.1最初出现该函数,2.3中有所改变。如果没有参数传入,该函数返回False。
callable( object)
Return true if the object argument appears callable, false if
not. If this returns true, it is still possible that a call fails, but if it is
false, calling object will never succeed. Note that classes are
callable (calling a class returns a new instance); class instances are callable
if they have a __call__() method.
如果对象参数是可调用的,该函数返回True,反之为False。如果返回True,同样有可能调用失败,但是如果返回False,就绝对不可能调用成功。注意这些类是可以调用的(调用一个类返回一个新实例),如果一个类有__call__()方法就可以调用类实例。
chr( i)
Return a string of one character whose ASCII code is the integer
i. For example, chr(97) returns the string
'a'. This is the inverse of ord(). The
argument must be in the range [0..255], inclusive; ValueError will be raised if i is outside that
range.
返回一个字符串,其ASCII码是一个整型i.比如chr(97)返回字符串’a'。参数i的范围在0-255之间。
classmethod( function)
Return a class method for function.

A class method receives the class as implicit first argument, just like an
instance method receives the instance. To declare a class method, use this
idiom:

一个类方法接受类,将其作为隐式的第一个参数,就像实例方法接受实例一样。声明一个类方法是用如下方式:

class C:
@classmethod 类方法的定义
def f(cls, arg1, arg2, ...): ...

The @classmethod form is a function decorator – see the
description of function definitions in chapter 7 of the Python Reference
Manual
for details.

It can be called either on the class (such as C.f()) or on an
instance (such as C().f()). 本句说明了调用类函数的方法和规范。The instance is ignored except for its
class. If a class method is called for a derived class, the derived class object
is passed as the implied first argument.如果一个类方法调用了一个此类的派生类,这个派生类对象就作为这个类函数的隐式的第一个参数。

Class methods are different than C++ or Java static methods. If you want
those, see staticmethod() in this section. New in version 2.2. Changed in
version 2.4: Function decorator syntax added.python的类函数不同于C++和Java的静态方法。如果你希望得到静态的方法,参考本节staticmethod()方法。本函数在2.4版中有新的发展:提供了函数描述的语法

cmp( x, y)
Compare the two objects x and y and return an integer
according to the outcome. The return value is negative if x
< y
, zero if x == y and
strictly positive if x > y.
比较俩个对象x和y,并且返回比较的结果。如果x<y,返回负值,x=y,返回0,x>y,返回正值
compile( string, filename, kind[,
flags
[,
dont_inherit
]])
Compile the string into a code object. Code objects can be
executed by an exec statement or evaluated by a call to
eval(). The filename argument should give the
file from which the code was read; pass some recognizable value if it wasn’t
read from a file ('<string>' is commonly used). The
kind argument specifies what kind of code must be compiled; it can be
'exec' if string consists of a sequence of statements,
'eval' if it consists of a single expression, or
'single' if it consists of a single interactive statement (in the
latter case, expression statements that evaluate to something else than
None will be printed).
本函数将字符串编译成代码对象,并可以被exec语句执行,或者被evel()求值。filename参数指定所需要的字符串是从哪个文件得到的,,如果没有从该指定文件中得到所需要的string,就将传递一些有标示性的值(string参数一般都是必须的)。kind参数指定必须编译成哪种类型的代码,如果string包含了程序语句序列就可以被exec函数执行,如果包含的仅仅是一个单语句就可以被evel函数执行,。。。(最后一句怎么解释,知道者请指教!不胜感激!)

When compiling multi-line statements, two caveats apply: line endings must be
represented by a single newline character ('\n'), and the input
must be terminated by at least one newline character. If line endings are
represented by '\r\n', use the string replace() method to change them into '\n'.

如果是多行语句,有以下两个要注意的:

1、每一行的结尾必须有换行符\n,并且输入部分必须被至少一个换行符终止;

2、如果行的结尾是’\r\n’,就必须使用replace()方法将之转换成’\n’。

The optional arguments flags and dont_inherit (which
are new in Python 2.2) control which future statements (see PEP 236) affect the compilation of string.
If neither is present (or both are zero) the code is compiled with those future
statements that are in effect in the code that is calling compile. If the
flags argument is given and dont_inherit is not (or is
zero) then the future statements specified by the flags argument are
used in addition to those that would be used anyway. If dont_inherit
is a non-zero integer then the flags argument is it – the future
statements in effect around the call to compile are ignored.

Future statemants are specified by bits which can be bitwise or-ed together
to specify multiple statements. The bitfield required to specify a given feature
can be found as the compiler_flag attribute on the _Feature instance in the __future__
module.

complex( [real[,
imag
]])
Create a complex number with the value real + imag*j
or convert a string or number to a complex number. If the first parameter is a
string, it will be interpreted as a complex number and the function must be
called without a second parameter. The second parameter can never be a string.
Each argument may be any numeric type (including complex). If imag is
omitted, it defaults to zero and the function serves as a numeric conversion
function like int(), long() and
float(). If both arguments are omitted, returns
0j.
创建一个复数类型。每个参数必须是数值类型,如果imag参数没有,默认为0,如果real和imag参数均无,则返回0j
delattr(


object, name)
This is a relative of setattr(). The arguments are
an object and a string. The string must be the name of one of the object’s
attributes. The function deletes the named attribute, provided the object allows
it. For example, delattr(x, 'foobar') is
equivalent to del x.foobar.
与setattr()相关的一组函数。参数是由一个对象(记住python中一切皆是对象)和一个字符串组成的。string参数必须是对象属性名之一。该函数删除该obj的一个由string指定的属性。delattr(x, 'foobar')=del x.foobar
dict( [mapping-or-sequence])
Return a new dictionary initialized from an optional positional argument or
from a set of keyword arguments. If no arguments are given, return a new empty
dictionary. If the positional argument is a mapping object, return a dictionary
mapping the same keys to the same values as does the mapping object. Otherwise
the positional argument must be a sequence, a container that supports iteration,
or an iterator object. The elements of the argument must each also be of one of
those kinds, and each must in turn contain exactly two objects. The first is
used as a key in the new dictionary, and the second as the key’s value. If a
given key is seen more than once, the last value associated with it is retained
in the new dictionary.
该函数返回一个新的dict初始对象,是从一个可选择的位置开始或者从一些列关键字参数中创建的(这句话怎么翻译更好?希望大家指教!)如果没有参数传入,创建一个新的空dict。如果位置参数是一个映射对象,就返回同映射对象一样的dict。另外,位置参数必须是序列sequence,一个支持跌代的容器,或者跌代对象。每一个元素必须有两个对象,第一个代表新字典的键,第二个代表字典的键值。如果一个关键键出现两次,保留最后一个键。

If keyword arguments are given, the keywords themselves with their associated
values are added as items to the dictionary. If a key is specified both in the
positional argument and as a keyword argument, the value associated with the
keyword is retained in the dictionary.

如果出现关键字参数,这些关键字自身及其相关的键值就作为一个项目被加入这个dict中。如果一个键同时被指定位置参数和作为一个关键字参数,与其关键字相关的值被保留在dict中。

 For example, these all return a
dictionary equal to {"one": 2, "two": 3}:

以下用法均等同于{‘one’:2,‘two’:3}

  • dict({'one': 2, 'two': 3})
  • dict({'one': 2, 'two': 3}.items())
  • dict({'one': 2, 'two': 3}.iteritems())
  • dict(zip(('one', 'two'), (2, 3)))
  • dict([['two', 3], ['one', 2]])
  • dict(one=2, two=3)
  • dict([(['one', 'two'][i-2], i) for i in (2, 3)])

New in version 2.2. Changed in version 2.3: Support for building a dictionary from
keyword arguments added.

======================================2006.2.15翻译
dir( [object])
Without arguments, return the list of names in the current local symbol
table. With an argument, attempts to return a list of valid attributes for that
object. This information is gleaned from the object’s __dict__ attribute, if defined, and from the class or type
object. The list is not necessarily complete. If the object is a module object,
the list contains the names of the module’s attributes. If the object is a type
or class object, the list contains the names of its attributes, and recursively
of the attributes of its bases. Otherwise, the list contains the object’s
attributes’ names, the names of its class’s attributes, and recursively of the
attributes of its class’s base classes. The resulting list is sorted
alphabetically. For example:

>>> import struct
>>> dir()
['__builtins__', '__doc__', '__name__', 'struct']
>>> dir(struct)
['__doc__', '__name__', 'calcsize', 'error', 'pack', 'unpack']

Note: Because dir() is supplied primarily as a convenience for use at an
interactive prompt, it tries to supply an interesting set of names more than it
tries to supply a rigorously or consistently defined set of names, and its
detailed behavior may change across releases.

这个函数经常使用,一般均是在交互模式.个人体会.在实际的编程应用当中,很少使用,但是不妨碍其成为python中的重要部分.个人非常推崇.:)
divmod( a, b)
Take two (non complex) numbers as arguments and return a pair of numbers
consisting of their quotient and remainder when using long division. With mixed
operand types, the rules for binary arithmetic operators apply. For plain and
long integers, the result is the same as (a / b,
a % b)
. For floating point numbers the result is
(q, a % b), where q is
usually math.floor(a / b) but may be 1 less
than that. In any case q * b + a %
b
is very close to a, if a %
b
is non-zero it has the same sign as b, and
0 <= abs(a % b) < abs(b).

Changed in version 2.3: Using divmod() with complex numbers is deprecated.

将两个非复数类型的数值作为参数,得到商和余数.数学应用.注意其参数的类型必须要匹配,尤其注意plain和浮点.b不能为0.不能用复数作为参数,否则返回错误.
enumerate( iterable)
Return an enumerate object. iterable must be a sequence, an
iterator, or some other object which supports iteration. The next() method of the iterator returned by enumerate() returns a tuple containing a count (from zero)
and the corresponding value obtained from iterating over
iterable.
enumerate() is useful for obtaining an indexed series:
(0, seq[0]), (1, seq[1]), (2, seq[2]),
…. New in version 2.3.
返回一个枚举对象.iterable必须是一个序列\跌代器,或者其他的支持跌代的对象.本函数最有用的地方是由此获得索引序列.
中间部分不知道怎么翻译.请指教.
eval( expression[, globals[,
locals
]])
The arguments are a string and optional globals and locals. If provided,
globals must be a dictionary. If provided, locals can be
any mapping object. Changed in version 2.4: formerly
locals was required to be a dictionary.
参数是字符串格式,可选择globals或者locals.如果可能的话,globals一定要是一个dict格式对象,而locals可以是任何映射对象格式.2.4版中不再限定locals必须是dict格式对象.

The expression argument is parsed and evaluated as a Python
expression (technically speaking, a condition list) using the globals
and locals dictionaries as global and local name space. If the
globals dictionary is present and lacks ‘__builtins__’, the current
globals are copied into globals before expression is
parsed. This means that expression normally has full access to the
standard __builtin__
module and restricted environments are propagated. If the locals
dictionary is omitted it defaults to the globals dictionary. If both
dictionaries are omitted, the expression is executed in the environment where
eval is called. The return value is the result of the
evaluated expression. Syntax errors are reported as exceptions.

expression()参数被python解释器分析,并且作为一个python表达式(从技术上来说,是一个条件列表)来执行,并且根据globals和locals参数给定的范围作为全局或者本地名称空间。如果globals字典存在,并且没有__builtins__,在expression被解析之前当前全局变量被复制成globals。这就意味着expression必须传入__builtins__,并且防止环境参数的变化。

Example:

>>> x = 1
>>> print eval('x+1')
2

This function can also be used to execute arbitrary code objects (such as
those created by compile()). In this case pass a code
object instead of a string. The code object must have been compiled passing
'eval' as the kind argument.

Hints: dynamic execution of statements is supported by the exec statement. Execution of statements from a file is
supported by the execfile() function. The globals() and locals() functions
returns the current global and local dictionary, respectively, which may be
useful to pass around for use by eval() or execfile().

execfile( filename[, globals[,
locals
]])
This function is similar to the exec statement, but
parses a file instead of a string. It is different from the import statement in that it does not use the module
administration — it reads the file unconditionally and does not create a new
module.2.2

The arguments are a file name and two optional dictionaries. The file is
parsed and evaluated as a sequence of Python statements (similarly to a module)
using the globals and locals dictionaries as global and
local namespace. If provided, locals can be any mapping object. Changed in version 2.4: formerly locals was
required to be a dictionary.
If the locals dictionary is
omitted it defaults to the globals dictionary. If both dictionaries
are omitted, the expression is executed in the environment where execfile() is called. The return value is None.

Warning: The default locals
act as described for function locals() below:
modifications to the default locals dictionary should not be
attempted. Pass an explicit locals dictionary if you need to see
effects of the code on locals after function execfile() returns. execfile()
cannot be used reliably to modify a function’s locals.

file( filename[, mode[,
bufsize
]])
Return a new file object (described in section 2.3.9, “File Objects”). The first two arguments are
the same as for stdio’s fopen():
filename is the file name to be opened, mode indicates how
the file is to be opened: 'r' for reading, 'w' for
writing (truncating an existing file), and 'a' opens it for
appending (which on some Unix systems means
that all writes append to the end of the file, regardless of the
current seek position).

Modes 'r+', 'w+' and 'a+' open the
file for updating (note that 'w+' truncates the file). Append
'b' to the mode to open the file in binary mode, on systems that
differentiate between binary and text files (else it is ignored). If the file
cannot be opened, IOError is raised.

In addition to the standard fopen() values
mode may be 'U' or 'rU'. If Python is built
with universal newline support (the default) the file is opened as a text file,
but lines may be terminated by any of '\n', the Unix end-of-line
convention, '\r', the Macintosh convention or '\r\n',
the Windows convention. All of these external representations are seen as
'\n' by the Python program. If Python is built without universal
newline support mode 'U' is the same as normal text
mode. Note that file objects so opened also have an attribute called newlines which has a value of None (if no
newlines have yet been seen), '\n', '\r',
'\r\n', or a tuple containing all the newline types seen.

If mode is omitted, it defaults to 'r'. When opening
a binary file, you should append 'b' to the mode value
for improved portability. (It’s useful even on systems which don’t treat binary
and text files differently, where it serves as documentation.) The optional bufsize argument specifies the
file’s desired buffer size: 0 means unbuffered, 1 means line buffered, any other
positive value means use a buffer of (approximately) that size. A negative
bufsize means to use the system default, which is usually line
buffered for tty devices and fully buffered for other files. If omitted, the
system default is used.2.3

The file() constructor is new in Python 2.2. The
previous spelling, open(), is retained for
compatibility, and is an alias for file().

filter( function, list)
Construct a list from those elements of list for which
function returns true. list may be either a sequence, a
container which supports iteration, or an iterator, If list is a
string or a tuple, the result also has that type; otherwise it is always a list.
If function is None, the identity function is assumed,
that is, all elements of list that are false (zero or empty) are
removed.

Note that filter(function, list) is equivalent to
[item for item in list if function(item)] if function is
not None and [item for item in list if
item]
if function is None.

float( [x])
Convert a string or a number to floating point. If the argument is a string,
it must contain a possibly signed decimal or floating point number, possibly
embedded in whitespace. Otherwise, the argument may be a plain or long integer
or a floating point number, and a floating point number with the same value
(within Python’s floating point precision) is returned. If no argument is given,
returns 0.0.

Note: When passing in a string, values
for NaN and Infinity may be returned, depending on the underlying C library. The
specific set of strings accepted which cause these values to be returned depends
entirely on the C library and is known to vary.

frozenset( [iterable])
Return a frozenset object whose elements are taken from iterable.
Frozensets are sets that have no update methods but can be hashed and used as
members of other sets or as dictionary keys. The elements of a frozenset must be
immutable themselves. To represent sets of sets, the inner sets should also be
frozenset objects. If iterable is not specified,
returns a new empty set, frozenset([]). New
in version 2.4.
getattr( object, name[,
default
])
Return the value of the named attributed of object.
name must be a string. If the string is the name of one of the
object’s attributes, the result is the value of that attribute. For example,
getattr(x, 'foobar') is equivalent to x.foobar. If the
named attribute does not exist, default is returned if provided,
otherwise AttributeError is raised.
globals( )
Return a dictionary representing the current global symbol table. This is
always the dictionary of the current module (inside a function or method, this
is the module where it is defined, not the module from which it is called).
hasattr( object, name)
The arguments are an object and a string. The result is True if
the string is the name of one of the object’s attributes, False if
not. (This is implemented by calling getattr(object,
name)
and seeing whether it raises an exception or not.)
hash( object)
Return the hash value of the object (if it has one). Hash values are
integers. They are used to quickly compare dictionary keys during a dictionary
lookup. Numeric values that compare equal have the same hash value (even if they
are of different types, as is the case for 1 and 1.0).
help( [object])
Invoke the built-in help system. (This function is intended for interactive
use.) If no argument is given, the interactive help system starts on the
interpreter console. If the argument is a string, then the string is looked up
as the name of a module, function, class, method, keyword, or documentation
topic, and a help page is printed on the console. If the argument is any other
kind of object, a help page on the object is generated. New in version 2.2.
hex( x)
Convert an integer number (of any size) to a hexadecimal string. The result
is a valid Python expression. Changed in version 2.4:
Formerly only returned an unsigned literal..
id( object)
Return the “identity” of an object. This is an integer (or long integer)
which is guaranteed to be unique and constant for this object during its
lifetime. Two objects with non-overlapping lifetimes may have the same id() value. (Implementation note: this is the address of the
object.)
input( [prompt])
Equivalent to eval(raw_input(prompt)). Warning: This function is not safe from user
errors! It expects a valid Python expression as input; if the input is not
syntactically valid, a SyntaxError will be raised.
Other exceptions may be raised if there is an error during evaluation. (On the
other hand, sometimes this is exactly what you need when writing a quick script
for expert use.)

If the readline
module was loaded, then input() will use it to provide
elaborate line editing and history features.

Consider using the raw_input() function for general
input from users.

int( [x[,
radix
]])
Convert a string or number to a plain integer. If the argument is a string,
it must contain a possibly signed decimal number representable as a Python
integer, possibly embedded in whitespace. The radix parameter gives
the base for the conversion and may be any integer in the range [2, 36], or
zero. If radix is zero, the proper radix is guessed based on the
contents of string; the interpretation is the same as for integer literals. If
radix is specified and x is not a string, TypeError is raised. Otherwise, the argument may be a plain
or long integer or a floating point number. Conversion of floating point numbers
to integers truncates (towards zero). If the argument is outside the integer
range a long object will be returned instead. If no arguments are given, returns
0.
isinstance( object, classinfo)
Return true if the object argument is an instance of the
classinfo argument, or of a (direct or indirect) subclass thereof.
Also return true if classinfo is a type object and object
is an object of that type. If object is not a class instance or an
object of the given type, the function always returns false. If
classinfo is neither a class object nor a type object, it may be a
tuple of class or type objects, or may recursively contain other such tuples
(other sequence types are not accepted). If classinfo is not a class,
type, or tuple of classes, types, and such tuples, a TypeError exception is raised. Changed in version 2.2: Support for a tuple of type
information was added.
issubclass( class, classinfo)
Return true if class is a subclass (direct or indirect) of
classinfo. A class is considered a subclass of itself.
classinfo may be a tuple of class objects, in which case every entry
in classinfo will be checked. In any other case, a TypeError exception is raised. Changed in version 2.3: Support for a tuple of type
information was added.
iter( o[,
sentinel
])
Return an iterator object. The first argument is interpreted very
differently depending on the presence of the second argument. Without a second
argument, o must be a collection object which supports the iteration
protocol (the __iter__() method), or it must support the
sequence protocol (the __getitem__() method with integer
arguments starting at 0). If it does not support either of those
protocols, TypeError is raised. If the second argument,
sentinel, is given, then o must be a callable object. The
iterator created in this case will call o with no arguments for each
call to its next() method; if the value returned is equal
to sentinel, StopIteration will be raised,
otherwise the value will be returned. New in version
2.2.
len( s)
Return the length (the number of items) of an object. The argument may be a
sequence (string, tuple or list) or a mapping (dictionary).
list( [sequence])
Return a list whose items are the same and in the same order as
sequence’s items. sequence may be either a sequence, a
container that supports iteration, or an iterator object. If sequence
is already a list, a copy is made and returned, similar to
sequence[:]. For instance, list('abc')
returns ['a', 'b', 'c'] and list( (1, 2, 3) ) returns
[1, 2, 3]. If no argument is given, returns a new empty list,
[].
locals( )
Update and return a dictionary representing the current local symbol table.
Warning: The contents of this dictionary
should not be modified; changes may not affect the values of local variables
used by the interpreter.
long( [x[,
radix
]])
Convert a string or number to a long integer. If the argument is a string,
it must contain a possibly signed number of arbitrary size, possibly embedded in
whitespace. The radix argument is interpreted in the same way as for
int(), and may only be given when x is a
string. Otherwise, the argument may be a plain or long integer or a floating
point number, and a long integer with the same value is returned. Conversion of
floating point numbers to integers truncates (towards zero). If no arguments are
given, returns 0L.
map( function, list, …)
Apply function to every item of list and return a list
of the results. If additional list arguments are passed,
function must take that many arguments and is applied to the items of
all lists in parallel; if a list is shorter than another it is assumed to be
extended with None items. If function is
None, the identity function is assumed; if there are multiple list
arguments, map() returns a list consisting of tuples
containing the corresponding items from all lists (a kind of transpose
operation). The list arguments may be any kind of sequence; the
result is always a list.
max( s[,
args...
])
With a single argument s, return the largest item of a non-empty
sequence (such as a string, tuple or list). With more than one argument, return
the largest of the arguments.
min( s[,
args...
])
With a single argument s, return the smallest item of a non-empty
sequence (such as a string, tuple or list). With more than one argument, return
the smallest of the arguments.
object( )
Return a new featureless object. object() is a base
for all new style classes. It has the methods that are common to all instances
of new style classes. New in version 2.2.

Changed in version 2.3: This function does not accept
any arguments. Formerly, it accepted arguments but ignored them.

oct( x)
Convert an integer number (of any size) to an octal string. The result is a
valid Python expression. Changed in version 2.4:
Formerly only returned an unsigned literal..
open( filename[, mode[,
bufsize
]])
An alias for the file() function above.
ord( c)
Return the ASCII value of a string of one character or a Unicode character.
E.g., ord('a') returns the integer 97,
ord(u'\u2020') returns 8224. This is the inverse of
chr() for strings and of unichr() for Unicode characters.
pow( x, y[,
z
])
Return x to the power y; if z is present,
return x to the power y, modulo z (computed
more efficiently than pow(x, y) %
z
). The arguments must have numeric types. With mixed operand
types, the coercion rules for binary arithmetic operators apply. For int and
long int operands, the result has the same type as the operands (after coercion)
unless the second argument is negative; in that case, all arguments are
converted to float and a float result is delivered. For example,
10**2 returns 100, but 10**-2 returns
0.01. (This last feature was added in Python 2.2. In Python 2.1 and
before, if both arguments were of integer types and the second argument was
negative, an exception was raised.) If the second argument is negative, the
third argument must be omitted. If z is present, x and
y must be of integer types, and y must be non-negative.
(This restriction was added in Python 2.2. In Python 2.1 and before, floating
3-argument pow() returned platform-dependent results depending on
floating-point rounding accidents.)
property( [fget[,
fset
[, fdel[,
doc
]]]])
Return a property attribute for new-style classes (classes that derive from
object).

fget is a function for getting an attribute value, likewise
fset is a function for setting, and fdel a function for
del’ing, an attribute. Typical use is to define a managed attribute x:

class C(object):
def getx(self): return self.__x
def setx(self, value): self.__x = value
def delx(self): del self.__x
x = property(getx, setx, delx, "I'm the 'x' property.")

New in version 2.2.

range( [start,]
stop
[,
step
])
This is a versatile function to create lists containing arithmetic
progressions. It is most often used in for loops. The
arguments must be plain integers. If the step argument is omitted, it
defaults to 1. If the start argument is omitted, it
defaults to 0. The full form returns a list of plain integers
[start, start + step, start +
2 * step, ...]
. If step is positive, the last
element is the largest start + i *
step
less than stop; if step is
negative, the last element is the largest start + i
* step
greater than stop. step must not
be zero (or else ValueError is raised). Example:

>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1, 11)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> range(0, 30, 5)
[0, 5, 10, 15, 20, 25]
>>> range(0, 10, 3)
[0, 3, 6, 9]
>>> range(0, -10, -1)
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
>>> range(0)
[]
>>> range(1, 0)
[]
raw_input( [prompt])
If the prompt argument is present, it is written to standard
output without a trailing newline. The function then reads a line from input,
converts it to a string (stripping a trailing newline), and returns that. When
EOF is read, EOFError is raised. Example:

>>> s = raw_input('--> ')
--> Monty Python's Flying Circus
>>> s
"Monty Python's Flying Circus"

If the readline
module was loaded, then raw_input() will use it to
provide elaborate line editing and history features.

reduce( function, sequence[,
initializer
])
Apply function of two arguments cumulatively to the items of
sequence, from left to right, so as to reduce the sequence to a
single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4,
5])
calculates ((((1+2)+3)+4)+5). The left argument,
x, is the accumulated value and the right argument, y, is
the update value from the sequence. If the optional
initializer is present, it is placed before the items of the sequence
in the calculation, and serves as a default when the sequence is empty. If
initializer is not given and sequence contains only one
item, the first item is returned.
reload( module)
Reload a previously imported module. The argument must be a
module object, so it must have been successfully imported before. This is useful
if you have edited the module source file using an external editor and want to
try out the new version without leaving the Python interpreter. The return value
is the module object (the same as the module argument).

When reload(module) is executed:

  • Python modules’ code is recompiled and the module-level code reexecuted,
    defining a new set of objects which are bound to names in the module’s
    dictionary. The init function of extension modules is not called a
    second time.

  • As with all other objects in Python the old objects are only reclaimed after
    their reference counts drop to zero.

  • The names in the module namespace are updated to point to any new or changed
    objects.

  • Other references to the old objects (such as names external to the module)
    are not rebound to refer to the new objects and must be updated in each
    namespace where they occur if that is desired.

There are a number of other caveats:

If a module is syntactically correct but its initialization fails, the first
import statement for it does not bind its name locally,
but does store a (partially initialized) module object in
sys.modules. To reload the module you must first import it again (this will bind the name to the partially
initialized module object) before you can reload() it.

When a module is reloaded, its dictionary (containing the module’s global
variables) is retained. Redefinitions of names will override the old
definitions, so this is generally not a problem. If the new version of a module
does not define a name that was defined by the old version, the old definition
remains. This feature can be used to the module’s advantage if it maintains a
global table or cache of objects — with a try statement
it can test for the table’s presence and skip its initialization if desired:

try:
cache
except NameError:
cache = {}

It is legal though generally not very useful to reload built-in or
dynamically loaded modules, except for sys, __main__ and __builtin__. In many cases, however,
extension modules are not designed to be initialized more than once, and may
fail in arbitrary ways when reloaded.

If a module imports objects from another module using fromimport …, calling reload() for the other module does not redefine the objects
imported from it — one way around this is to re-execute the from statement, another is to use import and qualified names
(module.name) instead.

If a module instantiates instances of a class, reloading the module that
defines the class does not affect the method definitions of the instances —
they continue to use the old class definition. The same is true for derived
classes.

repr( object)
Return a string containing a printable representation of an object. This is
the same value yielded by conversions (reverse quotes). It is sometimes useful
to be able to access this operation as an ordinary function. For many types,
this function makes an attempt to return a string that would yield an object
with the same value when passed to eval().
reversed( seq)
Return a reverse iterator. seq must be an object which supports
the sequence protocol (the __len__() method and the __getitem__() method with integer arguments starting at
0). New in version 2.4.
round( x[,
n
])
Return the floating point value x rounded to n digits
after the decimal point. If n is omitted, it defaults to zero. The
result is a floating point number. Values are rounded to the closest multiple of
10 to the power minus n; if two multiples are equally close, rounding
is done away from 0 (so. for example, round(0.5) is
1.0 and round(-0.5) is -1.0).
set( [iterable])
Return a set whose elements are taken from iterable. The elements
must be immutable. To represent sets of sets, the inner sets should be frozenset objects. If iterable is not specified,
returns a new empty set, set([]). New in
version 2.4.
setattr( object, name, value)
This is the counterpart of getattr(). The arguments
are an object, a string and an arbitrary value. The string may name an existing
attribute or a new attribute. The function assigns the value to the attribute,
provided the object allows it. For example, setattr(x,
'foobar', 123)
is equivalent to
x.foobar = 123.
slice( [start,]
stop
[,
step
])
Return a slice object representing the set of indices specified by
range(start, stop, step). The
start and step arguments default to None.
Slice objects have read-only data attributes start, stop and step which merely return the
argument values (or their default). They have no other explicit functionality;
however they are used by Numerical Python and
other third party extensions. Slice objects are also generated when extended
indexing syntax is used. For example: "a[start:stop:step]"
or "a[start:stop, i]".
sorted( iterable[, cmp[,
key
[,
reverse
]]])
Return a new sorted list from the items in iterable. The optional
arguments cmp, key, and reverse have the same
meaning as those for the list.sort() method. New in version 2.4.
staticmethod( function)
Return a static method for function.

A static method does not receive an implicit first argument. To declare a
static method, use this idiom:

class C:
@staticmethod
def f(arg1, arg2, ...): ...

The @staticmethod form is a function decorator – see the
description of function definitions in chapter 7 of the Python Reference
Manual
for details.

It can be called either on the class (such as C.f()) or on an
instance (such as C().f()). The instance is ignored except for its
class.

Static methods in Python are similar to those found in Java or C++. For a
more advanced concept, see classmethod() in this
section. New in version 2.2. Changed in version 2.4: Function decorator syntax
added.

str( [object])
Return a string containing a nicely printable representation of an object.
For strings, this returns the string itself. The difference with
repr(object) is that str(object)
does not always attempt to return a string that is acceptable to eval(); its goal is to return a printable string. If no
argument is given, returns the empty string, ''.
sum( sequence[,
start
])
Sums start and the items of a sequence, from left to
right, and returns the total. start defaults to 0. The
sequence’s items are normally numbers, and are not allowed to be
strings. The fast, correct way to concatenate sequence of strings is by calling
''.join(sequence). Note that
sum(range(n), m) is equivalent to
reduce(operator.add, range(n), m) New in version 2.3.
super( type[,
object-or-type
])
Return the superclass of type. If the second argument is omitted
the super object returned is unbound. If the second argument is an object,
isinstance(obj, type) must be true. If the
second argument is a type, issubclass(type2,
type)
must be true. super() only works
for new-style classes.

A typical use for calling a cooperative superclass method is:

class C(B):
def meth(self, arg):
super(C, self).meth(arg)

Note that super is implemented as part of the binding
process for explicit dotted attribute lookups such as "super(C,
self).__getitem__(name)
". Accordingly, super is
undefined for implicit lookups using statements or operators such as "super(C, self)[name]". New in version
2.2.

tuple( [sequence])
Return a tuple whose items are the same and in the same order as
sequence’s items. sequence may be a sequence, a container
that supports iteration, or an iterator object. If sequence is
already a tuple, it is returned unchanged. For instance,
tuple('abc') returns ('a', 'b', 'c') and
tuple([1, 2, 3]) returns (1, 2, 3). If no argument is
given, returns a new empty tuple, ().
type( object)
Return the type of an object. The return value is a type object. The standard module types defines names for all
built-in types that don’t already have built-in names. For instance:

>>> import types
>>> x = 'abc'
>>> if type(x) is str: print "It's a string"
...
It's a string
>>> def f(): pass
...
>>> if type(f) is types.FunctionType: print "It's a function"
...
It's a function

The isinstance() built-in function is recommended for
testing the type of an object.

unichr( i)
Return the Unicode string of one character whose Unicode code is the integer
i. For example, unichr(97) returns the string
u'a'. This is the inverse of ord() for
Unicode strings. The argument must be in the range [0..65535], inclusive. ValueError is raised otherwise. New
in version 2.0.
unicode( [object[, encoding
[,
errors
]]])
Return the Unicode string version of object using one of the
following modes:

If encoding and/or errors are given,
unicode() will decode the object which can either be an 8-bit
string or a character buffer using the codec for encoding. The
encoding parameter is a string giving the name of an encoding; if the
encoding is not known, LookupError is raised. Error
handling is done according to errors; this specifies the treatment of
characters which are invalid in the input encoding. If errors is
'strict' (the default), a ValueError is
raised on errors, while a value of 'ignore' causes errors to be
silently ignored, and a value of 'replace' causes the official
Unicode replacement character, U+FFFD, to be used to replace input
characters which cannot be decoded. See also the codecs module.

If no optional parameters are given, unicode() will mimic the
behaviour of str() except that it returns Unicode strings instead
of 8-bit strings. More precisely, if object is a Unicode string or
subclass it will return that Unicode string without any additional decoding
applied.

For objects which provide a __unicode__() method, it
will call this method without arguments to create a Unicode string. For all
other objects, the 8-bit string version or representation is requested and then
converted to a Unicode string using the codec for the default encoding in
'strict' mode.

New in version 2.0. Changed in version 2.2: Support for __unicode__() added.

vars( [object])
Without arguments, return a dictionary corresponding to the current local
symbol table. With a module, class or class instance object as argument (or
anything else that has a __dict__ attribute), returns a
dictionary corresponding to the object’s symbol table. The returned dictionary
should not be modified: the effects on the corresponding symbol table are
undefined.2.4
xrange( [start,]
stop
[,
step
])
This function is very similar to range(), but
returns an “xrange object” instead of a list. This is an opaque sequence type
which yields the same values as the corresponding list, without actually storing
them all simultaneously. The advantage of xrange() over
range() is minimal (since xrange() still has to create the values when asked for them)
except when a very large range is used on a memory-starved machine or when all
of the range’s elements are never used (such as when the loop is usually
terminated with break).

Note: xrange() is
intended to be simple and fast. Implementations may impose restrictions to
achieve this. The C implementation of Python restricts all arguments to native C
longs ("short" Python integers), and also requires that the number of elements
fit in a native C long.

zip( [seq1,
...
])
This function returns a list of tuples, where the i-th tuple
contains the i-th element from each of the argument sequences. The
returned list is truncated in length to the length of the shortest argument
sequence. When there are multiple argument sequences which are all of the same
length, zip() is similar to map() with an initial argument of None. With a
single sequence argument, it returns a list of 1-tuples. With no arguments, it
returns an empty list. New in version 2.0.

Changed in version 2.4: Formerly, zip() required at least one argument and zip()
raised a TypeError instead of returning an empty
list..

听说省上的达标检查组20号就要来了。要背好多的文件阿。累人哟。
今天都14号了,情人节!可惜没和女朋友一起去看电影,好多年了,不知道是不是自己感觉心态变老的一种表现,不过其实我一直都不是太在意这个节日,毕竟是外国人的嘛。
条条款款还好说,关键就是N多的数值,什么法律是什么时候开始的、具体的达标要求是什么、管理年活动的基本目的和任务是什么,听说还要抽人去考试。晕!
我什么都记不住,可是看起来好像那些不该干的事情我都没干,不知道对我个人而言是不是达标了?
哈哈,要是可以个人达标就好了!
中国就是形式主义严重!
BS一下!
呼呼去了,明天还要上班呢!

2006年02月14日

1. Introduction

The “Python library” contains several different kinds of components.

python library包含了很多不同的部分

It contains data types that would normally be considered part of the “core”
of a language, such as numbers and lists. For these types, the Python language
core defines the form of literals and places some constraints on their
semantics, but does not fully define the semantics. (On the other hand, the
language core does define syntactic properties like the spelling and priorities
of operators.)

它包含数据类型(这是语言的核心部分),比如数值、列表等。在本书中定义数据类型的书写形式以及部分语义。

The library also contains built-in functions and exceptions — objects that
can be used by all Python code without the need of an import statement. Some of these are defined by the core
language, but many are not essential for the core semantics and are only
described here.

本书还包含了内置函数和例外,这些内置函数和例外不需要使用import语句,而在所有的python代码中频繁使用。其中一部分是python的核心成分,但是很大一部分不是必须的,而在本书中只是简单描述。

The bulk of the library, however, consists of a collection of modules. There
are many ways to dissect this collection. Some modules are written in C and
built in to the Python interpreter; others are written in Python and imported in
source form. Some modules provide interfaces that are highly specific to Python,
like printing a stack trace; some provide interfaces that are specific to
particular operating systems, such as access to specific hardware; others
provide interfaces that are specific to a particular application domain, like
the World Wide Web. Some modules are available in all versions and ports of
Python; others are only available when the underlying system supports or
requires them; yet others are available only when a particular configuration
option was chosen at the time when Python was compiled and installed.

本书主要集中在大量的module的描述。有一些module是用c语言写成的,而还有一些是用python的,以源程序的形式被导入。一些module提供了python中非常特殊的借口,比如打印出堆栈;一些 module提供了与特定的操作系统的接口,比如操作特定的硬件;还有一些module提供了操作特殊领域的接口,比如连接www。一些module是在所有版本的python中均存在,还有一些只是在特定系统支持下才能使用的,还有部分是在特定的规范或者特定的时间中才使用的。

This manual is organized “from the inside out:” it first describes the
built-in data types, then the built-in functions and exceptions, and finally the
modules, grouped in chapters of related modules. The ordering of the chapters as
well as the ordering of the modules within each chapter is roughly from most
relevant to least important.

本手册的组织形式是“由内而外”。本书的module是依照相互关联的形式组织的。

This means that if you start reading this manual from the start, and skip to
the next chapter when you get bored, you will get a reasonable overview of the
available modules and application areas that are supported by the Python
library. Of course, you don’t have to read it like a novel — you can
also browse the table of contents (in front of the manual), or look for a
specific function, module or term in the index (in the back). And finally, if
you enjoy learning about random subjects, you choose a random page number (see
module random) and read a
section or two. Regardless of the order in which you read the sections of this
manual, it helps to start with chapter 2,
“Built-in Types, Exceptions and Functions,” as the remainder of the manual
assumes familiarity with this material.

本书 的阅读顺序 是必须依序而行的,这样你就可以获得比较合理连贯的概念。

Let the show begin!

加油吧!

2006年02月09日

我在医院,现在国家要对医院进行3年一次的复审了!

最怕这种审查了!手续复杂,形势单一,结果复杂,标准也很难把握!

不知道要经历多少“磨难”阿!

am

今天感到很郁闷,其实由来已久了。
很多学习python的程序老手,可是没有一个地方能让我们这些绝对新手来学习python。
limodou老师的网站上很多东西很深奥,学起来有点点困难。
肥肥论坛上问题太少,而且人气不足。
linux论坛上同limodou老师的站点一样,人气很足,但是不适合完全不会编程的人。


恩恩,乱说了一通,心情好了。呵呵,其实不能怪这些站点了,毕竟他们不可能为了满足我们这些完全的新手 而浪费很多的时间来指导我们,而我们这种完全的新手们应该在学习python之前或了解python的基本概念之后多学学其他的计算机的基础知识,然后多加融合,我相信一定会成功的。

希望各位初步涉及python的朋友们多多交流一下。
我的mail:oneclubw@gmail.com
        qq:      328250402
        google talk:oneclubw@gmail.com
       msn:    oneclubw@hotmail.com


请多多交流!
支持开源!支持python!

2006年02月07日

Pmw.MegaArchetype


Name

Pmw.MegaArchetype() –
abstract base class for all Pmw megawidgets


Description

This class is the basis for all Pmw megawidgets. It provides
methods to manage options and component widgets.

This class is normally used as a base class for other classes. If
the hullClass argument is specified, such as in the Pmw.MegaWidget
and Pmw.MegaToplevel classes, a container widget is created to act
as the parent of all other component widgets. Classes derived
from these sub classes create other component widgets and options
to implement megawidgets that can be used in applications.

If no hullClass argument is given to the constructor, no
container widget is created and only the option configuration
functionality is available.


Components

A megawidget is generally made up of other widgets packed
within the megawidget’s containing widget. These sub-widgets
are called the components of the megawidget and are given
logical names for easy reference. The component mechanism
allows the user of a megawidget to gain controlled access to
some of the internals of the megawidget, for example to call a
method of a component or to set a component’s configuration
options.

Sub components: If a component is itself a megawidget containing
sub-components, then these sub-components can be referred to
using the notation component_subcomponent. For example,
Pmw.ComboBox has a component named entryfield which is an
instance of Pmw.EntryField, which itself has a Tkinter.Entry
component named entry. In the context of the combobox, this
entry widget can be referred to as entryfield_entry.

Component aliases: Because the sub-component notation may
make component names inconveniently long, components and
sub-components can be aliased to simpler names. For example,
the entryfield_entry sub-component of Pmw.ComboBox is aliased
to simply entry. If there is no conflict in component
names, sub-component names are usually aliased to the name of
the "leaf" component.

Component groups: Similar components of a megawidget can be
given a group name, which allows all components of a group
to be referenced using the one group name. For example, the
two arrow components of Pmw.Counter have a group name of Arrow.
Also, megawidgets that can create an unlimited number of
similar components, such as Pmw.ButtonBox, create each of these
components with the same group name. By convention, group
names begin with a capital letter.


Options

A megawidget defines options which allow the megawidget user
to modify the appearance and behaviour of the megawidget.
Using the same technique as Tkinter widgets, the values of
megawidget options may be set in calls to the constructor and
to configure() and the values may be queried by calls to
cget() and configure(). Like Tkinter widgets, megawidget
options are initialised with default values. Also, if the
useTkOptionDb option to Pmw.initialise() has been set,
then the Tk option database will be queried to get the initial
values. Strings found in the option database are converted
to python objects (integer, float, tuple, dictionary, etc)
using a restricted eval() call. Anything that is not accepted by
eval() is treated as a string.

Inherited options: As well as the options defined in a class,
a derived class inherits all options of its base classes. The
default value of an option defined by a base class may be
modified by the derived class.

Initialisation options: Some megawidget options can only be
set in the call to the constructor. These are called
initialisation options. Unlike normal configuration
options, they cannot be set by calling the configure()
method.

Component options: Options of the components of a megawidget
can be referred to using the notation component_option.
Like the megawidget options, component options can be used in
calls to the constructor and to the cget() and configure()
methods. For example, the state option of the Tkinter.Text
text component of Pmw.ScrolledText may be set by calling

 widget.configure(text_state = 'disabled')

Sub-components, component aliases and component groups may
also be combined with options. For example, the state
option of the entryfield_entry component of Pmw.ComboBox
may be set by calling

 combobox.configure(entryfield_entry_state = 'normal')

Since it has an alias, it is more convenient to use the
equivalent form

 combobox.configure(entry_state = 'normal')

Also, the background color of both arrows of Pmw.Counter
can be set using the Arrow component group.

 counter.configure(Arrow_background = 'aliceblue')

The pyclass component option

The pyclass component option is a special notation that can
be used to specify a non-default python class for a component.
This can only be used when the component is being constructed.
For a component created during the construction of its parent
megawidget, this option must be given to the constructor in
the form component_pyclass. For example, to change the
python class of the text sub-component of Pmw.TextDialog
to a class FontText.Text

 dialog = Pmw.TextDialog(text_pyclass = FontText.Text)

For components created after the construction of the parent
megawidget, the pyclass option must be passed into the
method which constructs the component. For example, to set
the python class of a button in Pmw.ButtonBox to a class
MyButton:

 buttonBox.add('special', pyclass = MyButton)

The new python class of the component must support all methods
and options that are used by the megawidget when operating on
the component. The exact interface required for each
component is not documented. You will have to examine the Pmw
source code. However, any class derived from the default
class of a component can be used as the new class of the
component, as long as all of the original methods and options
are still supported. For example, any class derived from
Tkinter.Text can be used as the class of the text
sub-component of Pmw.TextDialog.

The pyclass component option should not be confused with the
class option that some of the Tk widgets support. The
class option sets the Tk option database class for the
widget and is used by Tk to query the database for the default
values of the widget’s other options. The name pyclass was
chosen so that it did not conflict with any known Tk options.


Construction

The constructors of classes derived from this class all accept
the same arguments: one positional argument and any number of
keyword arguments. The positional argument defaults to None
(meaning the root window) and specifies the widget to use as
the parent when creating the
megawidget’s hull component. The keyword arguments define
initial values for options. The format for the constructors
of derived classes is:

   def __init__(self, parent = None, **kw):


Methods

addoptions(optionDefs)
Add additional options for this megawidget. The optionDefs
argument is treated in the same way as for the defineoptions()
method.

This method is for use by derived classes. It is only used if a
megawidget should conditionally define some options, perhaps
depending on the value of other options. Usually, megawidgets
unconditionally define all their options in the call to
defineoptions() and do not need to use addoptions(). This
method must be called after the call to defineoptions() and
before the call to initialiseoptions().

cget(option)
Return the current value of option (which should be in the
format described in the Options section). This method is also
available using object subscripting, for example
myWidget['font']. Unlike Tkinter’s cget(), which always returns
a string, this method returns the same value and type as used when
the option was set (except where option is a component option
and the component is a Tkinter widget, in which case it returns
the string returned by Tcl/Tk).

component(name)
Return the component widget whose name is name. This
allows the user of a megawidget to access and configure component
widgets directly.

componentaliases()
Return the list of aliases for components. Each item in the list
is a tuple whose first item is the name of the alias and whose
second item is the name of the component or sub-component it
refers to.

componentgroup(name)
Return the group of the component whose name is name or None
if it does not have a group.

components()
Return a sorted list of names of the components of this
megawidget.

configure(option = None, **kw)
Query or configure the megawidget options.

If no arguments are given, return a tuple consisting of all
megawidget options and values, each as a 5-element tuple
(name, resourceName, resourceClass, default, value).
This is in the same format as the value returned by the standard
Tkinter configure() method, except that the resource name is
always the same as the option name and the resource class is the
option name with the first letter capitalised.

If one argument is given, return the 5 element tuple for option.

Otherwise, set the configuration options specified by the keyword
arguments. Each key should be in the format described in the
Options section.

createcomponent(componentName, componentAliases, componentGroup, widgetClass, *widgetArgs, **kw)
Create a component widget by calling widgetClass with the
arguments given by widgetArgs and any keyword arguments. The
componentName argument is the name by which the component will
be known and must not contain the underscore, ‘_’, character.
The componentGroup argument specifies the group of the
component. The componentAliases argument is a sequence of
2-element tuples, whose first item is an alias name and whose
second item is the name of the component or sub-component it is to
refer to.

If this method is called during megawidget construction, any
component options supplied to the megawidget constructor which
refer to this component (by componentName or componentGroup)
are added to the kw dictionary before calling widgetClass. If
the dictionary contains a ‘pyclass’ key, then this item is
removed from the dictionary and the value is used instead of
widgetClass. For more details see The pyclass component option
section.

This method may be called by derived classes during or after
megawidget construction. It returns the instance of the class
created.

createlabel(parent, childCols = 1, childRows = 1)
Create a Tkinter.Label component named ‘label’ in the parent
widget. This is a convenience method used by several megawidgets
that require an optional label. The widget must have options
named labelpos and labelmargin. If labelpos is None, no
label is created. Otherwise, a label is created and positioned
according to the value of labelpos and labelmargin. The label
is added to the parent using the grid() method, with childCols
and childRows indicating how many rows and columns the label
should span. Note that all other child widgets of the parent
must be added to the parent using the grid() method. The
createlabel() method may be called by derived classes during
megawidget construction.

defineoptions(keywords, optionDefs, dynamicGroups = ())
Create options for this megawidget. The optionDefs argument
defines the options. It is a sequence of 3-element tuples,
(name, default, callback), where name is the name of the
option, default is its default value and callback is the
function to call when the value of the option is set by a call to
configure(). The keywords argument should be the keyword
arguments passed in to the constructor of the megawidget. The user
may override the default value of an option by supplying a keyword
argument to the constructor.

If any option created by a base class is also defined by
optionDefs, then the derived class’s default value will take
precedence over the base class’s. If the callback field is not
None, then this will also override the callback set by the base
class.

If callback is Pmw.INITOPT, then the option is an
initialisation option.

The dynamicGroups argument contains a list of the groups of the
components created dynamically by this megawidget. If a group is
included in this list, then it not an error if a keyword argument
for the group is given to the constructor or to configure(),
even when no components with this group have been created.

If defineoptions() is called, it must be called once in the
megawidget constructor before the call to the constructor of the
base class and there must be a matching call to
initialiseoptions() at the end of the constructor.

destroy()
Destroy the hull component widget, if it exists, including all
of its children.

destroycomponent(name)
Remove the megawidget component called name. This method may be
called by derived classes to destroy a megawidget component. It
destroys the component widget and then removes all record of the
component from the megawidget.

hulldestroyed()
Return true if the Tk widget corresponding to the hull component
has been destroyed.

initialiseoptions(dummy = None)
Check keyword arguments and call option callback functions. This
method must be called, at the end of a megawidget constructor, if
and only if defineoptions() was also called in the constructor.
The dummy argument is not required, but is retained for
backwards compatibility.

It checks that all keyword arguments given to the constructor have
been used. If not, it raises an error indicating which arguments
were unused. A keyword is defined to be used if, during the
construction of a megawidget, it is defined in a call to
defineoptions() or addoptions() (by the megawidget or one of
its base classes), or it references, by name, a component of the
megawidget, or it references, by group, at least one component.
It also calls the configuration callback function for all options
that have a callback.

This method is only effective when called by the constructor of
the leaf class, that is, the class in the class hierarchy which
first called defineoptions(). For all other classes in the
class hierarchy (base classes), the method returns immediately.

interior()
Return the widget framing the interior space in which any children
of this megawidget should be created. By default, this returns
the hull component widget, if one was created, or None
otherwise. A subclass should use the widget returned by
interior() as the parent of any components or sub-widgets it
creates. Megawidgets which can be further subclassed, such as
Pmw.Dialog, should redefine this method to return the widget in
which subclasses should create children. The overall containing
widget is always available as the hull component.

isinitoption(option)
If option is an initialisation option, return true. Otherwise,
return false (the option is a configuration option). The option
argument must be an option of this megawidget, not an option of a
component. Otherwise an exception is raised.

options()
Return a sorted list of this megawidget’s options. Each item in
the list is a 3-element tuple, (option, default, isinit),
where option is the name of the option, default is its default
value and isinit is true if the option is an initialisation
option.

Using the Tk option database

有很多方法可以使用Tk的option数据来定制Pmw程序。首先你可用通过常规的方法来定制一个自己的基础Tk部件,比如设定所有的Tkinter.Label部件的bg色(不管是不是一个巨元件的组成部分)

root.option_add('*Label.background', 'pink')

设置所有的Pmw.EntryField的Label部件的bg的方法如下:

root.option_add('*EntryField.Label.background', 'green')
(编者注:注意蓝色字体部分!!!!)

而设置所有Pmw.EntryField组成部分的bg,包括hull部分的方法如下:

root.option_add('*EntryField*background', 'blue')

The above option settings affect basic Tk widgets and, since it is
built into the Tk widgets, this functionality is always available.

如果为了使用Tk的option数据来设置Pmw巨元件的默认值,Pmw.initialise()必须要跟上useTkOption=1。即Pmw.initialise(useTkOptionDb=1)

假定已经执行了上述语句,默认的Pmw.Dialog元件的位置设置如下所示:

root.option_add('*Dialog.buttonboxpos', 'e')

设定Pmw.EntryField元件的Label的默认位置如下所示:

root.option_add('*EntryField.labelpos', 'w')