📄 chap1.txt
字号:
float.__mul__(self, other)
float.__rmul__(self, other)
Return the product of 'self' and 'other'. Determines how a
datatype responds to the '*' operator.
float.__neg__(self)
Return the negative of 'self'. Determines how a datatype
responds to the unary '-' operator.
float.__pow__(self, other)
float.__rpow__(self, other)
Return 'self' raised to the 'other' power. Determines how
a datatype responds to the '^' operator.
float.__sub__(self, other)
float.__rsub__(self, other)
Return the difference between 'self' and 'other'.
Determines how a datatype responds to the binary '-'
operator.
float.__truediv__(self, other)
float.__rtruediv__(self, other)
Return the ratio of 'self' and 'other'. Determines how a
datatype responds to the Python 2.3+ true division operator
'/'.
SEE ALSO, [complex], [int], `float`, [operator]
=================================================================
BUILTIN -- complex : New-style base class for complex numbers
=================================================================
Complex numbers implement all the above documented methods of
floating point numbers, and a few additional ones.
Inequality operations on complex numbers are not supported in
recent versions of Python, even though they were previously. In
Python 2.1+, the methods `complex.__ge__()`, `complex.__gt__()`
`complex.__le__()`, and `complex.__lt__()` all raise 'TypeError'
rather than return Boolean values indicating the order. There is
a certain logic to this change inasmuch as complex numbers do not
have a "natural" ordering. But there is also significant
breakage with this change--this is one of the few changes in
Python, since version 1.4 when I started using it, that I feel
was a real mistake. The important breakage comes when you
want to sort a list of various things, some of which might be
complex numbers:
>>> lst = ["string", 1.0, 1, 1L, ('t','u','p')]
>>> lst.sort()
>>> lst
[1.0, 1, 1L, 'string', ('t', 'u', 'p')]
>>> lst.append(1j)
>>> lst.sort()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: cannot compare complex numbers using <, <=, >, >=
It is true that there is no obvious correct ordering between a
complex number and another number (complex or otherwise), but
there is also no natural ordering between a string, a tuple, and
a number. Nonetheless, it is frequently useful to sort a
heterogeneous list in order to create a canonical (even if
meaningless) order. In Python 2.2+, you can remedy this
shortcoming of recent Python versions in the style below (under
2.1 you are largely out of luck):
>>> class C(complex):
... def __lt__(self, o):
... if hasattr(o, 'imag'):
... return (self.real,self.imag) < (o.real,o.imag)
... else:
... return self.real < o
... def __le__(self, o): return self < o or self==o
... def __gt__(self, o): return not (self==o or self < o)
... def __ge__(self, o): return self > o or self==o
...
>>> lst = ["str", 1.0, 1, 1L, (1,2,3), C(1+1j), C(2-2j)]
>>> lst.sort()
>>> lst
[1.0, 1, 1L, (1+1j), (2-2j), 'str', (1, 2, 3)]
Of course, if you adopt this strategy, you have to create all
of your complex values using the custom datatype 'C'. And
unfortunately, unless you override arithmetic operations also,
a binary operation between a 'C' object and another number
reverts to a basic complex datatype. The reader can work out
the details of this solution if she needs it.
METHODS:
complex.conjugate(self)
Return the complex conjugate of 'self'. A quick refresher
here: If 'self' is 'n+mj' its conjugate is 'n-mj'.
complex.imag
Imaginary component of a complex number.
complex.real
Real component of a complex number.
SEE ALSO, [float], `complex`
=================================================================
MODULE -- UserDict : Custom wrapper around dictionary objects
=================================================================
BUILTIN -- dict : New-style base class for dictionary objects
=================================================================
Dictionaries in Python provide a well-optimized mapping between
immutable objects and other Python objects (see Glossary entry
on "immutable"). You may create custom datatypes that respond
to various dictionary operations. There are a few syntactic
operations associated with dictionaries, all involving indexing
with square braces. But unlike with numeric datatypes, there
are several regular methods that are reasonable to consider as
part of the general interface for dictionary-like objects.
If you create a dictionary-like datatype by subclassing from
`UserDict.UserDict`, all the special methods defined by the
parent are proxies to the true dictionary stored in the
object's '.data' member. If, under Python 2.2+, you subclass
from 'dict' itself, the object itself inherits dictionary
behaviors. In either case, you may customize whichever methods
you wish. Below is an example of the two styles for
subclassing a dictionary-like datatype:
>>> from sys import stderr
>>> from UserDict import UserDict
>>> class LogDictOld(UserDict):
... def __setitem__(self, key, val):
... stderr.write("Set: "+str(key)+"->"+str(val)+"\n")
... self.data[key] = val
...
>>> ldo = LogDictOld()
>>> ldo['this'] = 'that'
Set: this->that
>>> class LogDictNew(dict):
... def __setitem__(self, key, val):
... stderr.write("Set: "+str(key)+"->"+str(val)+"\n")
... dict.__setitem__(self, key, val)
...
>>> ldn = LogDictOld()
>>> ldn['this'] = 'that'
Set: this->that
METHODS:
dict.__cmp__(self, other)
UserDict.UserDict.__cmp__(self, other)
Return a value indicating the order of 'self' and 'other'.
Determines how a datatype responds to the numeric comparison
operators '<', '>', '<=', '>=', '==', '<>', and '!='. Also
determines the behavior of the built-in `cmp()` function.
Should return -1 for 'self<other', 0 for 'self==other', and
1 for 'self>other'. If other comparison methods are
defined, they take precedence over '.__cmp__()':
'.__ge__()', '.__gt__()', '.__le__()', and '.__lt__()'.
dict.__contains__(self, x)
UserDict.UserDict.__contains__(self, x)
Return a Boolean value indicating whether 'self' "contains"
the value 'x'. By default, being contained in a dictionary
means matching one of its keys, but you can change this
behavior by overriding it (e.g., check whether 'x' is in a
value rather than a key). Determines how a datatype
responds to the 'in' operator.
dict.__delitem__(self, x)
UserDict.UserDict.__delitem__(self, x)
Remove an item from a dictionary-like datatype. By
default, removing an item means removing the pair whose
key equals 'x'. Determines how a datatype responds to the
'del' statement, as in: 'del self[x]'.
dict.__getitem__(self, x)
UserDict.UserDict.__getitem__(self, x)
By default, return the value associated with the key 'x'.
Determines how a datatype responds to indexing with square
braces. You may override this method to either search
differently or return special values. For example:
>>> class BagOfPairs(dict):
... def __getitem__(self, x):
... if self.has_key(x):
... return (x, dict.__getitem__(self,x))
... else:
... tmp = dict([(v,k) for k,v in self.items()])
... return (dict.__getitem__(tmp,x), x)
...
>>> bop = BagOfPairs({'this':'that', 'spam':'eggs'})
>>> bop['this']
('this', 'that')
>>> bop['eggs']
('spam', 'eggs')
>>> bop['bacon'] = 'sausage'
>>> bop
{'this': 'that', 'bacon': 'sausage', 'spam': 'eggs'}
>>> bop['nowhere']
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 7, in __getitem__
KeyError: nowhere
dict.__len__(self)
UserDict.UserDict.__len__(self)
Return the length of the dictionary. By default this is
simply a count of the key/val pairs, but you could perform
a different calculation if you wished (e.g, perhaps you
would cache the size of a record set returned from a
database query that emulated a dictionary). Determines how
a datatype responds to the built-in `len()` function.
dict.__setitem__(self, key, val)
UserDict.UserDict.__setitem__(self, key, val)
Set the dictionary key 'key' to value 'val'. Determines
how a datatype responds to indexed assignment; that is,
'self[key]=val'. A custom version might actually perform
some calculation based on 'val' and/or 'key' before adding
an item.
dict.clear(self)
UserDict.UserDict.clear(self)
Remove all items from 'self'.
dict.copy(self)
UserDict.UserDict.copy(self)
Return a copy of the dictionary 'self' (i.e., a distinct
object with the same items).
dict.get(self, key [,default=None])
UserDict.UserDict.get(self, key [,default=None])
Return the value associated with the key 'key'. If no item
with the key exists, return 'default' instead of raising a
'KeyError'.
dict.has_key(self, key)
UserDict.UserDict.has_key(self, key)
Return a Boolean value indicating whether 'self' has the
key 'key'.
dict.items(self)
UserDict.UserDict.items(self)
dict.iteritems(self)
UserDict.UserDict.iteritems(self)
Return the items in a dictionary, in an unspecified order.
The '.items()' method returns a true list of '(key,val)'
pairs, while the '.iteritems()' method (in Python 2.2+)
returns a generator object that successively yields items.
The latter method is useful if your dictionary is not a
true in-memory structure, but rather some sort of
incremental query or calculation. Either method responds
externally similarly to a 'for' loop:
>>> d = {1:2, 3:4}
>>> for k,v in d.iteritems(): print k,v,':',
...
1 2 : 3 4 :
>>> for k,v in d.items(): print k,v,':',
...
1 2 : 3 4 :
dict.keys(self)
UserDict.UserDict.keys(self)
dict.iterkeys(self)
UserDict.UserDict.iterkeys(self)
Return the keys in a dictionary, in an unspecified order.
The '.keys()' method returns a true list of keys, while the
'.iterkeys()' method (in Python 2.2+) returns a generator
object.
SEE ALSO, `dict.items()`
dict.popitem(self)
UserDict.UserDict.popitem(self)
Return a '(key,val)' pair for the dictionary, or raise as
'KeyError' if the dictionary is empty. Removes the
returned item from the dictionary. As with other
dictionary methods, the order in which items are popped is
unspecified (and can vary between versions and platforms).
dict.setdefault(self, key [,default=None])
UserDict.UserDict.setdefault(self, key [,default=None])
If 'key' is currently in the dictionary, return the
corresponding value. If 'key' is not currently in the
dictionary, set 'self[key]=default', then return 'default'.
SEE ALSO, `dict.get()`
dict.update(self, other)
UserDict.UserDict.update(s
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -