python—基础类的那点儿所以然
有道是:‘要知其然,更要知其所以然’~~~那么今天就来说点儿所以然,对python中的int,str,lst,dict和tuple等基础类中的方法做一些解析
那么类是什么呢?
官方的解释是这样的:对象是对客观事物的抽象,类是对对象的抽象。
因此str是类,int是类,dict、list、tuple等等都是类,但是str却不能直接使用,因为它是抽象的表示了字符串这一类事物,并不能满足表示某个特定字符串的需求,我们必须要str1 = ''初始化一个对象,这时的str1具有str的属性,可以使用str中的方法。
类为我们创建对象,提供功能,在python中,一切事物都是对象!(瞧,谁还敢嫌弃我们程序员没有对象,我们可以new一个呀!)
在这里介绍些类、对象、方法的查看方式:
首先,需要装python,然后至少要有个命令行窗口:
查看对象的类型:type(对象名)如图所示:定义了一个平时经常会用到的字符串,但是我不知道它属于哪个类,type一下它就告诉我了。
1 >>> str1 = 'Eva_J'
2 >>> type(str1)
3 <type 'str'>
查看类的所有方法:dir(类名)如下,就打印出了所有的类方法。
1 >>> dir(str)
2 ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
那么问题来了,方法名为什么有的两边带着下划线,有的没有呢?那是python用来标识私有方法、非私有方法哒,带下划线的标识私有方法,他们通常拥有不止一种调用方 法。如下,我定义了两个字符串,__add__的+的效果是相同的。这里有一个内置方法很特殊:__init__,它是类中的构造方法,会在调用其所在类的时候自动执行。
1 >>> str1 = 'Eva_J'
2 >>> str2 = ' happy every day!'
3 >>> str1.__add__(str2)
4 'Eva_J happy every day!'
5 >>> str1+str2
6 'Eva_J happy every day!'
在python中,还有一个“help(类名.方法名)”方法:可以查看类的详细功能;“help(类名.功能名)”:查看类中某功能的详细情况
>>> help(str)
Help on class str in module __builtin__: class str(basestring)
| str(object='') -> string
|
| Return a nice string representation of the object.
| If the argument is a string, the return value is the same object.
|
| Method resolution order:
| str
| basestring
| object
|
| Methods defined here:
|
| __add__(...)
| x.__add__(y) <==> x+y
|
| __contains__(...)
| x.__contains__(y) <==> y in x
|
| __eq__(...)
| x.__eq__(y) <==> x==y
|
| __format__(...)
| S.__format__(format_spec) -> string
|
| Return a formatted version of S as described by format_spec.
|
| __ge__(...)
| x.__ge__(y) <==> x>=y
|
| __getattribute__(...)
| x.__getattribute__('name') <==> x.name
|
| __getitem__(...)
| x.__getitem__(y) <==> x[y]
|
| __getnewargs__(...)
|
| __getslice__(...)
| x.__getslice__(i, j) <==> x[i:j]
|
| Use of negative indices is not supported.
|
| __gt__(...)
| x.__gt__(y) <==> x>y
|
| __hash__(...)
| x.__hash__() <==> hash(x)
|
| __le__(...)
| x.__le__(y) <==> x<=y
|
| __len__(...)
| x.__len__() <==> len(x)
|
| __lt__(...)
| x.__lt__(y) <==> x<y
|
| __mod__(...)
| x.__mod__(y) <==> x%y
|
| __mul__(...)
| x.__mul__(n) <==> x*n
|
| __ne__(...)
| x.__ne__(y) <==> x!=y
|
| __repr__(...)
| x.__repr__() <==> repr(x)
|
| __rmod__(...)
| x.__rmod__(y) <==> y%x
|
| __rmul__(...)
| x.__rmul__(n) <==> n*x
|
| __sizeof__(...)
| S.__sizeof__() -> size of S in memory, in bytes
|
| __str__(...)
| x.__str__() <==> str(x)
|
| capitalize(...)
| S.capitalize() -> string
|
| Return a copy of the string S with only its first character
| capitalized.
|
| center(...)
| S.center(width[, fillchar]) -> string
|
| Return S centered in a string of length width. Padding is
| done using the specified fill character (default is a space)
|
| count(...)
| S.count(sub[, start[, end]]) -> int
|
| Return the number of non-overlapping occurrences of substring sub in
| string S[start:end]. Optional arguments start and end are interpreted
| as in slice notation.
|
| decode(...)
| S.decode([encoding[,errors]]) -> object
|
| Decodes S using the codec registered for encoding. encoding defaults
| to the default encoding. errors may be given to set a different error
| handling scheme. Default is 'strict' meaning that encoding errors raise
| a UnicodeDecodeError. Other possible values are 'ignore' and 'replace'
| as well as any other name registered with codecs.register_error that is
| able to handle UnicodeDecodeErrors.
|
| encode(...)
| S.encode([encoding[,errors]]) -> object
|
| Encodes S using the codec registered for encoding. encoding defaults
| to the default encoding. errors may be given to set a different error
| handling scheme. Default is 'strict' meaning that encoding errors raise
| a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
| 'xmlcharrefreplace' as well as any other name registered with
| codecs.register_error that is able to handle UnicodeEncodeErrors.
|
| endswith(...)
| S.endswith(suffix[, start[, end]]) -> bool
|
| Return True if S ends with the specified suffix, False otherwise.
| With optional start, test S beginning at that position.
| With optional end, stop comparing S at that position.
| suffix can also be a tuple of strings to try.
|
| expandtabs(...)
| S.expandtabs([tabsize]) -> string
|
| Return a copy of S where all tab characters are expanded using spaces.
| If tabsize is not given, a tab size of 8 characters is assumed.
|
| find(...)
| S.find(sub [,start [,end]]) -> int
|
| Return the lowest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Return -1 on failure.
|
| format(...)
| S.format(*args, **kwargs) -> string
|
| Return a formatted version of S, using substitutions from args and kwargs.
| The substitutions are identified by braces ('{' and '}').
|
| index(...)
| S.index(sub [,start [,end]]) -> int
|
| Like S.find() but raise ValueError when the substring is not found.
|
| isalnum(...)
| S.isalnum() -> bool
|
| Return True if all characters in S are alphanumeric
| and there is at least one character in S, False otherwise.
|
| isalpha(...)
| S.isalpha() -> bool
|
| Return True if all characters in S are alphabetic
| and there is at least one character in S, False otherwise.
|
| isdigit(...)
| S.isdigit() -> bool
|
| Return True if all characters in S are digits
| and there is at least one character in S, False otherwise.
|
| islower(...)
| S.islower() -> bool
|
| Return True if all cased characters in S are lowercase and there is
| at least one cased character in S, False otherwise.
|
| isspace(...)
| S.isspace() -> bool
|
| Return True if all characters in S are whitespace
| and there is at least one character in S, False otherwise.
|
| istitle(...)
| S.istitle() -> bool
|
| Return True if S is a titlecased string and there is at least one
| character in S, i.e. uppercase characters may only follow uncased
| characters and lowercase characters only cased ones. Return False
| otherwise.
|
| isupper(...)
| S.isupper() -> bool
|
| Return True if all cased characters in S are uppercase and there is
| at least one cased character in S, False otherwise.
|
| join(...)
| S.join(iterable) -> string
|
| Return a string which is the concatenation of the strings in the
| iterable. The separator between elements is S.
|
| ljust(...)
| S.ljust(width[, fillchar]) -> string
|
| Return S left-justified in a string of length width. Padding is
| done using the specified fill character (default is a space).
|
| lower(...)
| S.lower() -> string
|
| Return a copy of the string S converted to lowercase.
|
| lstrip(...)
| S.lstrip([chars]) -> string or unicode
|
| Return a copy of the string S with leading whitespace removed.
| If chars is given and not None, remove characters in chars instead.
| If chars is unicode, S will be converted to unicode before stripping
|
| partition(...)
| S.partition(sep) -> (head, sep, tail)
|
| Search for the separator sep in S, and return the part before it,
| the separator itself, and the part after it. If the separator is not
| found, return S and two empty strings.
|
| replace(...)
| S.replace(old, new[, count]) -> string
|
| Return a copy of string S with all occurrences of substring
| old replaced by new. If the optional argument count is
| given, only the first count occurrences are replaced.
|
| rfind(...)
| S.rfind(sub [,start [,end]]) -> int
|
| Return the highest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Return -1 on failure.
|
| rindex(...)
| S.rindex(sub [,start [,end]]) -> int
|
| Like S.rfind() but raise ValueError when the substring is not found.
|
| rjust(...)
| S.rjust(width[, fillchar]) -> string
|
| Return S right-justified in a string of length width. Padding is
| done using the specified fill character (default is a space)
|
| rpartition(...)
| S.rpartition(sep) -> (head, sep, tail)
|
| Search for the separator sep in S, starting at the end of S, and return
| the part before it, the separator itself, and the part after it. If the
| separator is not found, return two empty strings and S.
|
| rsplit(...)
| S.rsplit([sep [,maxsplit]]) -> list of strings
|
| Return a list of the words in the string S, using sep as the
| delimiter string, starting at the end of the string and working
| to the front. If maxsplit is given, at most maxsplit splits are
| done. If sep is not specified or is None, any whitespace string
| is a separator.
|
| rstrip(...)
| S.rstrip([chars]) -> string or unicode
|
| Return a copy of the string S with trailing whitespace removed.
| If chars is given and not None, remove characters in chars instead.
| If chars is unicode, S will be converted to unicode before stripping
|
| split(...)
| S.split([sep [,maxsplit]]) -> list of strings
|
| Return a list of the words in the string S, using sep as the
| delimiter string. If maxsplit is given, at most maxsplit
| splits are done. If sep is not specified or is None, any
| whitespace string is a separator and empty strings are removed
| from the result.
|
| splitlines(...)
| S.splitlines(keepends=False) -> list of strings
|
| Return a list of the lines in S, breaking at line boundaries.
| Line breaks are not included in the resulting list unless keepends
| is given and true.
|
| startswith(...)
| S.startswith(prefix[, start[, end]]) -> bool
|
| Return True if S starts with the specified prefix, False otherwise.
| With optional start, test S beginning at that position.
| With optional end, stop comparing S at that position.
| prefix can also be a tuple of strings to try.
|
| strip(...)
| S.strip([chars]) -> string or unicode
|
| Return a copy of the string S with leading and trailing
| whitespace removed.
| If chars is given and not None, remove characters in chars instead.
| If chars is unicode, S will be converted to unicode before stripping
|
| swapcase(...)
| S.swapcase() -> string
|
| Return a copy of the string S with uppercase characters
| converted to lowercase and vice versa.
|
| title(...)
| S.title() -> string
|
| Return a titlecased version of S, i.e. words start with uppercase
| characters, all remaining cased characters have lowercase.
|
| translate(...)
| S.translate(table [,deletechars]) -> string
|
| Return a copy of the string S, where all characters occurring
| in the optional argument deletechars are removed, and the
| remaining characters have been mapped through the given
| translation table, which must be a string of length 256 or None.
| If the table argument is None, no translation is applied and
| the operation simply removes the characters in deletechars.
|
| upper(...)
| S.upper() -> string
|
| Return a copy of the string S converted to uppercase.
|
| zfill(...)
| S.zfill(width) -> string
|
| Pad a numeric string S with zeros on the left, to fill a field
| of the specified width. The string S is never truncated.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __new__ = <built-in method __new__ of type object>
| T.__new__(S, ...) -> a new object with type S, a subtype of T
1 >>> help(str.find)
2 Help on method_descriptor:
3
4 find(...)
5 S.find(sub [,start [,end]]) -> int
6
7 Return the lowest index in S where substring sub is found,
8 such that sub is contained within S[start:end]. Optional
9 arguments start and end are interpreted as in slice notation.
10
11 Return -1 on failure.
不要小看了上面的这些方法,它对于看一段新的python代码也大有帮助~
源码解析:
下面是python中的一些基础类:
Int类:
所有方法:
1 >>> dir(int)
2 ['__abs__', '__add__', '__and__', '__clas s__', '__cmp__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__float__', '__floordiv__', '__format__', '__getattribute__', '__getnewargs__', '__hash__', '__hex__', '__index__', '__init__', '__int__', '__invert__', '__long__', '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'imag', 'numerator', 'real']
源码:
1 class int(object):
2 """
3 int(x=0) -> int or long
4 int(x, base=10) -> int or long
5
6 Convert a number or string to an integer, or return 0 if no arguments
7 are given. If x is floating point, the conversion truncates towards zero.
8 If x is outside the integer range, the function returns a long instead.
9
10 If x is not a number or if base is given, then x must be a string or
11 Unicode object representing an integer literal in the given base. The
12 literal can be preceded by '+' or '-' and be surrounded by whitespace.
13 The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to
14 interpret the base from the string as an integer literal.
15 >>> int('0b100', base=0)
16 4
17 """
18 def bit_length(self): # real signature unknown; restored from __doc__
19 """返回表示该数字时所用的最小位数
20 int.bit_length() -> int
21
22 Number of bits necessary to represent self in binary.
23 >>> bin(37)
24 '0b100101'
25 >>> (37).bit_length()
26 6
27 """
28 return 0
29
30 def conjugate(self, *args, **kwargs): # real signature unknown
31 """返回一个复数的共轭复数
32 Returns self, the complex conjugate of any int. """
33 pass
34
35 def __abs__(self): # real signature unknown; restored from __doc__
36 """ 返回绝对值
37 x.__abs__() <==> abs(x) """
38 pass
39
40 def __add__(self, y): # real signature unknown; restored from __doc__
41 """ 返回两个数的和
42 x.__add__(y) <==> x+y """
43 pass
44
45 def __and__(self, y): # real signature unknown; restored from __doc__
46 """ 返回两个数按位与的结果
47 x.__and__(y) <==> x&y """
48 pass
49
50 def __cmp__(self, y): # real signature unknown; restored from __doc__
51 """返回两个数比较的结果,参数从左至右(a,b),a>b返回1,a<b返回-1,a=b返回0
52 x.__cmp__(y) <==> cmp(x,y) """
53 pass
54
55 def __coerce__(self, y): # real signature unknown; restored from __doc__
56 """a.__coerce__(b),强制返回一个元组(a,b)
57 x.__coerce__(y) <==> coerce(x, y) """
58 pass
59
60 def __divmod__(self, y): # real signature unknown; restored from __doc__
61 """ 相除,得到商和余数组成的元组
62 x.__divmod__(y) <==> divmod(x, y) """
63 pass
64
65 def __div__(self, y): # real signature unknown; restored from __doc__
66 """返回两数相除的商
67 x.__div__(y) <==> x/y """
68 pass
69
70 def __float__(self): # real signature unknown; restored from __doc__
71 """将数据类型强制转换为float
72 x.__float__() <==> float(x) """
73 pass
74
75 def __floordiv__(self, y): # real signature unknown; restored from __doc__
76 """ 不保留小数点后的小数除法,也可以用‘//’来表示:a//b,我们亲切地称之为“地板除”!!!
77 x.__floordiv__(y) <==> x//y """
78 pass
79
80 def __format__(self, *args, **kwargs): # real signature unknown
81 """ 格式化"""
82 pass
83
84 def __getattribute__(self, name): # real signature unknown; restored from __doc__
85 """无条件被调用,通过实例访问属性
86 x.__getattribute__('name') <==> x.name """
87 pass
88
89 def __getnewargs__(self, *args, **kwargs): # real signature unknown
90 """ 内部调用 __new__方法或创建对象时传入参数使用 """
91 pass
92
93 def __hash__(self): # real signature unknown; restored from __doc__
94 """ 如果对象object为哈希表类型,返回对象object的哈希值。哈希值为整数。在字典查找中,哈希值用于快速比较字典的键。两个数值如果相等,则哈希值也相等
95 x.__hash__() <==> hash(x) """
96 pass
97
98 def __hex__(self): # real signature unknown; restored from __doc__
99 """ 返回当前数的 十六进制 表示
100 x.__hex__() <==> hex(x) """
101 pass
102
103 def __index__(self): # real signature unknown; restored from __doc__
104 """ 用于切片,对数字无意义
105 x[y:z] <==> x[y.__index__():z.__index__()] """
106 pass
107
108 def __init__(self, x, base=10): # known special case of int.__init__
109 """构造函数
110 int(x=0) -> int or long
111 int(x, base=10) -> int or long
112
113 Convert a number or string to an integer, or return 0 if no arguments
114 are given. If x is floating point, the conversion truncates towards zero.
115 If x is outside the integer range, the function returns a long instead.
116
117 If x is not a number or if base is given, then x must be a string or
118 Unicode object representing an integer literal in the given base. The
119 literal can be preceded by '+' or '-' and be surrounded by whitespace.
120 The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to
121 interpret the base from the string as an integer literal.
122 >>> int('0b100', base=0)
123 4
124 # (copied from class doc)
125 """
126 pass
127
128 def __int__(self): # real signature unknown; restored from __doc__
129 """ 转换为整数
130 x.__int__() <==> int(x) """
131 pass
132
133 def __invert__(self): # real signature unknown; restored from __doc__
134 """按位求反
135 x.__invert__() <==> ~x """
136 pass
137
138 def __long__(self): # real signature unknown; restored from __doc__
139 """转换为长整数
140 x.__long__() <==> long(x) """
141 pass
142
143 def __lshift__(self, y): # real signature unknown; restored from __doc__
144 """ 左移,相对二进制的操作
145 x.__lshift__(y) <==> x<<y """
146 pass
147
148 def __mod__(self, y): # real signature unknown; restored from __doc__
149 """ 取余
150 x.__mod__(y) <==> x%y """
151 pass
152
153 def __mul__(self, y): # real signature unknown; restored from __doc__
154 """ 返回两数相乘的积
155 x.__mul__(y) <==> x*y """
156 pass
157
158 def __neg__(self): # real signature unknown; restored from __doc__
159 """ 返回一个数的负数,个人觉得和相反数没差
160 x.__neg__() <==> -x """
161 pass
162
163 @staticmethod # known case of __new__
164 def __new__(S, *more): # real signature unknown; restored from __doc__
165 """ 创建一个int类的新对象
166 T.__new__(S, ...) -> a new object with type S, a subtype of T """
167 pass
168
169 def __nonzero__(self): # real signature unknown; restored from __doc__
170 """ 判断一个数是不是0
171 x.__nonzero__() <==> x != 0 """
172 pass
173
174 def __oct__(self): # real signature unknown; restored from __doc__
175 """ 返回该值的 八进制 表示
176 x.__oct__() <==> oct(x) """
177 pass
178
179 def __or__(self, y): # real signature unknown; restored from __doc__
180 """ 位运算,或,针对二进制数
181 x.__or__(y) <==> x|y """
182 pass
183
184 def __pos__(self): # real signature unknown; restored from __doc__
185 """ 并没什么卵用,说是a.__pos__(),会返回一个+a,但是不管输入整数还是负数,返回值都是他本身,感觉歪果仁真有幽默感
186 x.__pos__() <==> +x """
187 pass
188
189 def __pow__(self, y, z=None): # real signature unknown; restored from __doc__
190 """ 幂,次方
191 x.__pow__(y[, z]) <==> pow(x, y[, z]) """
192 pass
193
194 def __radd__(self, y): # real signature unknown; restored from __doc__
195 """x.__radd__(y) <==> y+x """
196 pass
197
198 def __rand__(self, y): # real signature unknown; restored from __doc__
199 """x.__rand__(y) <==> y&x """
200 pass
201
202 def __rdivmod__(self, y): # real signature unknown; restored from __doc__
203 """ x.__rdivmod__(y) <==> divmod(y, x) """
204 pass
205
206 def __rdiv__(self, y): # real signature unknown; restored from __doc__
207 """ x.__rdiv__(y) <==> y/x """
208 pass
209
210 def __repr__(self): # real signature unknown; restored from __doc__
211 """ 转化为解释器可读取的形式
212 x.__repr__() <==> repr(x) """
213 pass
214
215 def __rfloordiv__(self, y): # real signature unknown; restored from __doc__
216 """
217 x.__rfloordiv__(y) <==> y//x """
218 pass
219
220 def __rlshift__(self, y): # real signature unknown; restored from __doc__
221 """ x.__rlshift__(y) <==> y<<x """
222 pass
223
224 def __rmod__(self, y): # real signature unknown; restored from __doc__
225 """ x.__rmod__(y) <==> y%x """
226 pass
227
228 def __rmul__(self, y): # real signature unknown; restored from __doc__
229 """ x.__rmul__(y) <==> y*x """
230 pass
231
232 def __ror__(self, y): # real signature unknown; restored from __doc__
233 """ x.__ror__(y) <==> y|x """
234 pass
235
236 def __rpow__(self, x, z=None): # real signature unknown; restored from __doc__
237 """ y.__rpow__(x[, z]) <==> pow(x, y[, z]) """
238 pass
239
240 def __rrshift__(self, y): # real signature unknown; restored from __doc__
241 """ x.__rrshift__(y) <==> y>>x """
242 pass
243
244 def __rshift__(self, y): # real signature unknown; restored from __doc__
245 """ x.__rshift__(y) <==> x>>y """
246 pass
247
248 def __rsub__(self, y): # real signature unknown; restored from __doc__
249 """ x.__rsub__(y) <==> y-x """
250 pass
251
252 def __rtruediv__(self, y): # real signature unknown; restored from __doc__
253 """ x.__rtruediv__(y) <==> y/x """
254 pass
255
256 def __rxor__(self, y): # real signature unknown; restored from __doc__
257 """ x.__rxor__(y) <==> y^x """
258 pass
259
260 def __str__(self): # real signature unknown; restored from __doc__
261 """ 转换为人阅读的形式,如果没有适于人阅读的解释形式的话,则返回解释器课阅读的形式
262 x.__str__() <==> str(x) """
263 pass
264
265 def __sub__(self, y): # real signature unknown; restored from __doc__
266 """ 返回两数相减的差
267 x.__sub__(y) <==> x-y """
268 pass
269
270 def __truediv__(self, y): # real signature unknown; restored from __doc__
271 """返回两数相除的商,这里的除是精确的除法,不会省略小数点后的值
272 x.__truediv__(y) <==> x/y """
273 pass
274
275 def __trunc__(self, *args, **kwargs): # real signature unknown
276 """返回数值被截取为整形的值,在整形中无意义
277 Truncating an Integral returns itself. """
278 pass
279
280 def __xor__(self, y): # real signature unknown; restored from __doc__
281 """ 按位异或
282 x.__xor__(y) <==> x^y """
283 pass
284
285 denominator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
286 """ 分母 = 1 """
287 """the denominator of a rational number in lowest terms"""
288
289 imag = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
290 """ 虚数,无意义 """
291 """the imaginary part of a complex number"""
292
293 numerator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
294 """ 分子 = 数字大小 """
295 """the numerator of a rational number in lowest terms"""
296
297 real = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
298 """ 实数,无意义 """
299 """the real part of a complex number"""
int Code
我已经在源码中加入了注释,原谅我后面很多函数没有加注释都,因为那些前面在前面已近出现过了,只是在前面多了一个'r'的,比如and,变成了rand,在这里统一总结,就是参数的顺序从右到左反过来了。比如原本的a.__div__(b)是a/b,但是a.__rdiv__(b)的表示的就是b/a,对!就是这么坑爹!
在int类中,比较普通的就是+,-,*,/,%,位运算,进制间以及数据类型间的转换。下面对于比较特别但是常用的方法再进行一下记录:
(1) __cmp__:比较两个数的大小
1 >>> a = 12
2 >>> b = 15
3 >>> cmp(a,b) #比较两个参数的值,如果第一个参数小于第二个参数,返回-1
4 -1
5 >>> cmp(b,a) #比较两个参数的值,如果第一个参数大于第二个参数,返回1
6 1
7 >>> c = 12
8 >>> a.__cmp__(c) #比较两个参数的值,如果第一个参数大于第二个参数,返回0
9 0 #cmp方法也有两种调用方式
(2)__neg__/__abs__:取相反数/取绝对值
1 >>> a = -12
2 >>> b = 21
3 >>> a.__neg__() #求相反数
4 12
5 >>> b.__neg__()
6 -21
7 >>> a.__abs__() #求绝对值
8 12
9 >>> b.__abs__()
10 21
(3)__coerce__:强制返回一个元组(好吧,我承认这个并不常用,就是和divmod比较看看)
(4)__divmod__:返回两个数相除的商和余数组成的元组(商,余数) 应用:显示数据分页
1 >>> a = 102
2 >>> b = 10
3 >>> a.__divmod__(b)
4 (10, 2)
5 >>> a.__coerce__(b)
6 (102, 10)
(5)__floordiv__:不保留小数点后的小数除法,在这儿把所有的除法都整理了,然而我并没发现__div__和__floordiv__的区别啊~~~
1 >>> a = 13
2 >>> b = 2
3 >>> a.__div__(b)
4 6
5 >>> a.__truediv__(b)
6 6.5
7 >>> a.__floordiv__(b)
8 6
9 >>> a/b
10 6
11 >>> a//b
12 6
(6)__repr__/__str__:转化为解释器可读取的形式/转换为人阅读的形式
Long类:
>>> dir(long)
['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__float__', '__floordiv__', '__format__', '__getattribute__', '__getnewargs__', '__hash__', '__hex__', '__index__', '__init__', '__int__', '__invert__', '__long__', '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'imag', 'numerator', 'real']
长整形就是长长的整形。。。现在的操作系统大部分int类型的表示范围是2^32,而长整形就是2^64,在python里,不需要程序员手动的转换int和long的数据类型,当数值的大小超过了int的表示范围,python会自动将数据类型转换为long型,就是这么智能!!!既然long和int同表示整形,那么他们包含的方法也是差不多的,在这里就不再介绍了。
float类:
float类定义了类似3.14,6.28这样的小数。
>>> dir(float)
['__abs__', '__add__', '__class__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__eq__', '__float__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getformat__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__int__', '__le__', '__long__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__nonzero__', '__pos__', '__pow__', '__radd__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rmod__', '__rmul__', '__rpow__', '__rsub__', '__rtruediv__', '__setattr__', '__setformat__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', 'as_integer_ratio', 'conjugate', 'fromhex', 'hex', 'imag', 'is_integer', 'real']
我们在创建对象的时候,python也会很聪明的识别出float类型,在计算的时候也是这样,不管表达式中有多少整形多少浮点型,只要存在浮点型,那么所有计算都按照浮点型计算,得出的结果也会是float类型。其余方法和整形并没有太大差别,在这里也不做详细总结了。
>>> a = 3.14
>>> type(a)
<type 'float'>
>>> b = 6.28
>>> c = b/a
>>> print c,type(c)
2.0 <type 'float'>
>>> d = 8
>>> type(d)
<type 'int'>
>>> d/c
4.0
>>> type(d/c)
<type 'float'>
Str类:
>>> dir(str)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
class str(basestring):
"""
str(object='') -> string Return a nice string representation of the object.
If the argument is a string, the return value is the same object.
"""
def capitalize(self):
""" 首字母变大写 """
"""
S.capitalize() -> string Return a copy of the string S with only its first character
capitalized.
"""
return "" def center(self, width, fillchar=None):
""" 内容居中,width:总长度;fillchar:空白处填充内容,默认无 """
"""
S.center(width[, fillchar]) -> string Return S centered in a string of length width. Padding is
done using the specified fill character (default is a space)
"""
return "" def count(self, sub, start=None, end=None):
""" 子序列个数 """
"""
S.count(sub[, start[, end]]) -> int Return the number of non-overlapping occurrences of substring sub in
string S[start:end]. Optional arguments start and end are interpreted
as in slice notation.
"""
return 0 def decode(self, encoding=None, errors=None):
""" 解码 """
"""
S.decode([encoding[,errors]]) -> object Decodes S using the codec registered for encoding. encoding defaults
to the default encoding. errors may be given to set a different error
handling scheme. Default is 'strict' meaning that encoding errors raise
a UnicodeDecodeError. Other possible values are 'ignore' and 'replace'
as well as any other name registered with codecs.register_error that is
able to handle UnicodeDecodeErrors.
"""
return object() def encode(self, encoding=None, errors=None):
""" 编码,针对unicode """
"""
S.encode([encoding[,errors]]) -> object Encodes S using the codec registered for encoding. encoding defaults
to the default encoding. errors may be given to set a different error
handling scheme. Default is 'strict' meaning that encoding errors raise
a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
'xmlcharrefreplace' as well as any other name registered with
codecs.register_error that is able to handle UnicodeEncodeErrors.
"""
return object() def endswith(self, suffix, start=None, end=None):
""" 是否以 xxx 结束 """
"""
S.endswith(suffix[, start[, end]]) -> bool Return True if S ends with the specified suffix, False otherwise.
With optional start, test S beginning at that position.
With optional end, stop comparing S at that position.
suffix can also be a tuple of strings to try.
"""
return False def expandtabs(self, tabsize=None):
""" 将tab转换成空格,默认一个tab转换成8个空格 """
"""
S.expandtabs([tabsize]) -> string Return a copy of S where all tab characters are expanded using spaces.
If tabsize is not given, a tab size of 8 characters is assumed.
"""
return "" def find(self, sub, start=None, end=None):
""" 寻找子序列位置,如果没找到,则异常 """
"""
S.find(sub [,start [,end]]) -> int Return the lowest index in S where substring sub is found,
such that sub is contained within S[start:end]. Optional
arguments start and end are interpreted as in slice notation. Return -1 on failure.
"""
return 0 def format(*args, **kwargs): # known special case of str.format
""" 字符串格式化,动态参数,将函数式编程时细说 """
"""
S.format(*args, **kwargs) -> string Return a formatted version of S, using substitutions from args and kwargs.
The substitutions are identified by braces ('{' and '}').
"""
pass def index(self, sub, start=None, end=None):
""" 子序列位置,如果没找到,则返回-1 """
S.index(sub [,start [,end]]) -> int Like S.find() but raise ValueError when the substring is not found.
"""
return 0 def isalnum(self):
""" 是否是字母和数字 """
"""
S.isalnum() -> bool Return True if all characters in S are alphanumeric
and there is at least one character in S, False otherwise.
"""
return False def isalpha(self):
""" 是否是字母 """
"""
S.isalpha() -> bool Return True if all characters in S are alphabetic
and there is at least one character in S, False otherwise.
"""
return False def isdigit(self):
""" 是否是数字 """
"""
S.isdigit() -> bool Return True if all characters in S are digits
and there is at least one character in S, False otherwise.
"""
return False def islower(self):
""" 是否小写 """
"""
S.islower() -> bool Return True if all cased characters in S are lowercase and there is
at least one cased character in S, False otherwise.
"""
return False def isspace(self):
"""是否空格
S.isspace() -> bool Return True if all characters in S are whitespace
and there is at least one character in S, False otherwise.
"""
return False def istitle(self):
"""是否标题
S.istitle() -> bool Return True if S is a titlecased string and there is at least one
character in S, i.e. uppercase characters may only follow uncased
characters and lowercase characters only cased ones. Return False
otherwise.
"""
return False def isupper(self):
"""是否大写
S.isupper() -> bool Return True if all cased characters in S are uppercase and there is
at least one cased character in S, False otherwise.
"""
return False def join(self, iterable):
""" 连接 """
"""
S.join(iterable) -> string Return a string which is the concatenation of the strings in the
iterable. The separator between elements is S.
"""
return "" def ljust(self, width, fillchar=None):
""" 内容左对齐,右侧填充 """
"""
S.ljust(width[, fillchar]) -> string Return S left-justified in a string of length width. Padding is
done using the specified fill character (default is a space).
"""
return "" def lower(self):
""" 变小写 """
"""
S.lower() -> string Return a copy of the string S converted to lowercase.
"""
return "" def lstrip(self, chars=None):
""" 移除左侧空白 """
"""
S.lstrip([chars]) -> string or unicode Return a copy of the string S with leading whitespace removed.
If chars is given and not None, remove characters in chars instead.
If chars is unicode, S will be converted to unicode before stripping
"""
return "" def partition(self, sep):
""" 分割,前,中,后三部分 """
"""
S.partition(sep) -> (head, sep, tail) Search for the separator sep in S, and return the part before it,
the separator itself, and the part after it. If the separator is not
found, return S and two empty strings.
"""
pass def replace(self, old, new, count=None):
""" 替换 """
"""
S.replace(old, new[, count]) -> string Return a copy of string S with all occurrences of substring
old replaced by new. If the optional argument count is
given, only the first count occurrences are replaced.
"""
return "" def rfind(self, sub, start=None, end=None):
"""
S.rfind(sub [,start [,end]]) -> int Return the highest index in S where substring sub is found,
such that sub is contained within S[start:end]. Optional
arguments start and end are interpreted as in slice notation. Return -1 on failure.
"""
return 0 def rindex(self, sub, start=None, end=None):
"""
S.rindex(sub [,start [,end]]) -> int Like S.rfind() but raise ValueError when the substring is not found.
"""
return 0 def rjust(self, width, fillchar=None):
"""
S.rjust(width[, fillchar]) -> string Return S right-justified in a string of length width. Padding is
done using the specified fill character (default is a space)
"""
return "" def rpartition(self, sep):
"""
S.rpartition(sep) -> (head, sep, tail) Search for the separator sep in S, starting at the end of S, and return
the part before it, the separator itself, and the part after it. If the
separator is not found, return two empty strings and S.
"""
pass def rsplit(self, sep=None, maxsplit=None):
"""
S.rsplit([sep [,maxsplit]]) -> list of strings Return a list of the words in the string S, using sep as the
delimiter string, starting at the end of the string and working
to the front. If maxsplit is given, at most maxsplit splits are
done. If sep is not specified or is None, any whitespace string
is a separator.
"""
return [] def rstrip(self, chars=None):
"""
S.rstrip([chars]) -> string or unicode Return a copy of the string S with trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
If chars is unicode, S will be converted to unicode before stripping
"""
return "" def split(self, sep=None, maxsplit=None):
""" 分割, maxsplit最多分割几次 """
"""
S.split([sep [,maxsplit]]) -> list of strings Return a list of the words in the string S, using sep as the
delimiter string. If maxsplit is given, at most maxsplit
splits are done. If sep is not specified or is None, any
whitespace string is a separator and empty strings are removed
from the result.
"""
return [] def splitlines(self, keepends=False):
""" 根据换行分割 """
"""
S.splitlines(keepends=False) -> list of strings Return a list of the lines in S, breaking at line boundaries.
Line breaks are not included in the resulting list unless keepends
is given and true.
"""
return [] def startswith(self, prefix, start=None, end=None):
""" 是否起始 """
"""
S.startswith(prefix[, start[, end]]) -> bool Return True if S starts with the specified prefix, False otherwise.
With optional start, test S beginning at that position.
With optional end, stop comparing S at that position.
prefix can also be a tuple of strings to try.
"""
return False def strip(self, chars=None):
""" 移除两段空白 """
"""
S.strip([chars]) -> string or unicode Return a copy of the string S with leading and trailing
whitespace removed.
If chars is given and not None, remove characters in chars instead.
If chars is unicode, S will be converted to unicode before stripping
"""
return "" def swapcase(self):
""" 大写变小写,小写变大写 """
"""
S.swapcase() -> string Return a copy of the string S with uppercase characters
converted to lowercase and vice versa.
"""
return "" def title(self):
"""
S.title() -> string Return a titlecased version of S, i.e. words start with uppercase
characters, all remaining cased characters have lowercase.
"""
return "" def translate(self, table, deletechars=None):
"""
转换,需要先做一个对应表,最后一个表示删除字符集合
intab = "aeiou"
outtab = ""
trantab = maketrans(intab, outtab)
str = "this is string example....wow!!!"
print str.translate(trantab, 'xm')
""" """
S.translate(table [,deletechars]) -> string Return a copy of the string S, where all characters occurring
in the optional argument deletechars are removed, and the
remaining characters have been mapped through the given
translation table, which must be a string of length 256 or None.
If the table argument is None, no translation is applied and
the operation simply removes the characters in deletechars.
"""
return "" def upper(self):
"""
S.upper() -> string Return a copy of the string S converted to uppercase.
"""
return "" def zfill(self, width):
"""方法返回指定长度的字符串,原字符串右对齐,前面填充0。"""
"""
S.zfill(width) -> string Pad a numeric string S with zeros on the left, to fill a field
of the specified width. The string S is never truncated.
"""
return "" def _formatter_field_name_split(self, *args, **kwargs): # real signature unknown
pass def _formatter_parser(self, *args, **kwargs): # real signature unknown
pass def __add__(self, y):
""" x.__add__(y) <==> x+y """
pass def __contains__(self, y):
""" x.__contains__(y) <==> y in x """
pass def __eq__(self, y):
""" x.__eq__(y) <==> x==y """
pass def __format__(self, format_spec):
"""
S.__format__(format_spec) -> string Return a formatted version of S as described by format_spec.
"""
return "" def __getattribute__(self, name):
""" x.__getattribute__('name') <==> x.name """
pass def __getitem__(self, y):
""" x.__getitem__(y) <==> x[y] """
pass def __getnewargs__(self, *args, **kwargs): # real signature unknown
pass def __getslice__(self, i, j):
"""
x.__getslice__(i, j) <==> x[i:j] Use of negative indices is not supported.
"""
pass def __ge__(self, y):
""" x.__ge__(y) <==> x>=y """
pass def __gt__(self, y):
""" x.__gt__(y) <==> x>y """
pass def __hash__(self):
""" x.__hash__() <==> hash(x) """
pass def __init__(self, string=''): # known special case of str.__init__
"""
str(object='') -> string Return a nice string representation of the object.
If the argument is a string, the return value is the same object.
# (copied from class doc)
"""
pass def __len__(self):
""" x.__len__() <==> len(x) """
pass def __le__(self, y):
""" x.__le__(y) <==> x<=y """
pass def __lt__(self, y):
""" x.__lt__(y) <==> x<y """
pass def __mod__(self, y):
""" x.__mod__(y) <==> x%y """
pass def __mul__(self, n):
""" x.__mul__(n) <==> x*n """
pass @staticmethod # known case of __new__
def __new__(S, *more):
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass def __ne__(self, y):
""" x.__ne__(y) <==> x!=y """
pass def __repr__(self):
""" x.__repr__() <==> repr(x) """
pass def __rmod__(self, y):
""" x.__rmod__(y) <==> y%x """
pass def __rmul__(self, n):
""" x.__rmul__(n) <==> n*x """
pass def __sizeof__(self):
""" S.__sizeof__() -> size of S in memory, in bytes """
pass def __str__(self):
""" x.__str__() <==> str(x) """
pass str
str Code
接下来对于str类中一些常用的方法进行说明:
(1)capitalize:将首字母大写
>>> name = 'eva'
>>> name.capitalize()
'Eva'
(2)center/ljust/rjst:固定字符串长度,居中/居左/居右 ,下面是使用示例,当然没有正常人会上来就这么用,一般用在打印列表和字典的时候整理格式。
>>> str1.ljust(20,) #设置格式左对齐,其余部分默认情况下,以空格填充
'hello,Eva! '
>>> str1.center(20,'*') #设置格式左对齐,剩余部分已“*”填充
'*****hello,Eva!*****'
>>> str1.rjust(20,'&') #设置格式左对齐,剩余部分已“&”填充
'&&&&&&&&&&hello,Eva!'
(3)count:子序列个数,用来统计一个字符串中包含指定子序列的个数。这个子序列可以是一个字符,也可以是多个字符~~
>>> str1 = 'hello,Eva.Have a nice day'
>>> str1.count('a')
4
>>> str1.count('va')
1
(4)encode/decode:编码/解码,如下左图,各个编码之间是不能直接转换的,计算机内存中默认存储的编码格式是unicode,所以当我们需要将编码在utf8和gbk之间转换的时候,都需要和unicode做操作。
我的终端编码是gbk编码的,当我创建一个string = '景'时,string就被存储成gbk格式。此时我想把gbk格式转换成utf8格式,就要先将原gbk格式的string转换成unicode格式,然后再将unicode转换成utf8格式。如下右图,老师说,把这个字整乱码了我们的目的就达到了,哈~
(5)endswith:是否以...(子串)结尾。这里的子串依然可以是一个或多个字符。
>>> str1 = 'hello,Eva.Have a nice day'
>>> str1.endswith('day')
True
(6)expandtabs:将tab转换成空格,默认一个tab转换成8个空格。当然这里也可以自行指定转换成多少个空格,要不是怕写不下,我就指定它转成千八百个。。。
>>> name = ' Eva'
>>> name.expandtabs()
' Eva'
>>> name.expandtabs(20)
' Eva'
(7)find:返回字符串中第一个子序列的下标。
rfind:和find用法一样,只是它是从右向左查找
index:和find的左右一致,只是find找不到的时候会返回-1,而index找不到的时候会报错
值得注意的是,当我们在一个字符串中查找某一个子序列的时候,如果这个字符串中含有多个子序列,只会返回第一个找到的下标,不会返回其他的。
>>> name = 'hello,eva,how are you'
>>> name.find('o')
4
>>> name.find('t')
-1
>>> name.index('e')
1
>>> name.index('t') Traceback (most recent call last):
File "<pyshell#234>", line 1, in <module>
name.index('t')
ValueError: substring not found
(8)format:各种格式化,动态参数。
>>> str1 = 'I\'m {0},age {1}'
>>> str2 = 'I\'m {name},age {age}'
>>> lst = ['Eva','']
>>> dic = {'name':'Eva','age':''}
>>> str1.format('Eva','')
"I'm Eva,age 18"
>>> str1.format(*lst)
"I'm Eva,age 18"
>>> str2.format(age = '',name = 'Eva')
"I'm Eva,age 18"
>>> str2.format(**dic)
"I'm Eva,age 18"
(9)isalnum/isalpha/isdigit/isspace/islower/istitle/isupper:是否是字母或数字/是否字母/是否数字/是否空格/是否小写/是否标题/是否全大写,总之都是一些判断的方法,返回的不是True就是False。。。
(10)partition/split:这两个方法都用来分割。
partition会将指定的子串串提取并将子串两侧内容分割,只匹配一次,并返回元祖;
split会根据指定子串,将整个字符串所有匹配的子串匹配到并剔除,将其他内容分割,返回数组。
>>> food = 'apple,banana,chocolate'
>>> food.split(',')
['apple', 'banana', 'chocolate']
>>> food.partition(',')
('apple', ',', 'banana,chocolate')
(11)replace:替换。会替换字符串中所有符合条件的子串。。。原谅我的chinglish。。。
>>> str1 = 'I\'m Rita,Do you remember,Rita?'
>>> str1.replace('Rita','Eva')
"I'm Eva,Do you remember,Eva?"
(12)swapcase:大写变小写,小写变大写
>>> str1 = 'I\'m Eva'
>>> str1.swapcase()
"i'M eVA"
(13)translate:替换,删除字符串。这个方法的使用比较麻烦,在使用前需要引入string类,并调用其中的maketrans方法建立映射关系。这样,在translate方法中,加入映射参数,就可以看到效果了。如下‘aeiou’分别和‘12345’建立了映射关系,于是在最后,aeiou都被12345相应的替换掉了,translate第二个参数是删除,它删除了所有的‘.’
>>> in_tab = 'aeiou'
>>> out_tab = ''
>>> import string
>>> transtab = string.maketrans(in_tab,out_tab)
>>> str = 'this is a translate example...wow!'
>>> str1 = 'this is a translate example...wow!'
>>> print str1.translate(transtab,'..')
th3s 3s 1 tr1nsl1t2 2x1mpl2w4w!
List类:
>>> dir(list)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
class list(object):
"""
list() -> new empty list
list(iterable) -> new list initialized from iterable's items
"""在数组的末尾新增一项
def append(self, p_object): # real signature unknown; restored from __doc__
"""
L.append(object) -- append object to end """
pass def count(self, value): # real signature unknown; restored from __doc__
""" 查看lst中某一项出现的次数
L.count(value) -> integer -- return number of occurrences of value """
return 0 def extend(self, iterable): # real signature unknown; restored from __doc__
"""将原列表与其他列表扩展成新列表
L.extend(iterable) -- extend list by appending elements from the iterable """
pass def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
"""返回列表中第一个匹配项的下标,找不到会报错
L.index(value, [start, [stop]]) -> integer -- return first index of value.
Raises ValueError if the value is not present.
"""
return 0 def insert(self, index, p_object): # real signature unknown; restored from __doc__
"""在指定位置插入项
L.insert(index, object) -- insert object before index """
pass def pop(self, index=None): # real signature unknown; restored from __doc__
"""返回指定位置的值,并将其从列表中删除。默认对末尾项操作
L.pop([index]) -> item -- remove and return item at index (default last).
Raises IndexError if list is empty or index is out of range.
"""
pass def remove(self, value): # real signature unknown; restored from __doc__
"""从列表中移除第一个符合与指定值相等的项
L.remove(value) -- remove first occurrence of value.
Raises ValueError if the value is not present.
"""
pass def reverse(self): # real signature unknown; restored from __doc__
"""列表反转
L.reverse() -- reverse *IN PLACE* """
pass def sort(self, cmp=None, key=None, reverse=False): # real signature unknown; restored from __doc__
"""排序,数字、字符串按照ASCII,中文按照unicode从小到大排序。
L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
cmp(x, y) -> -1, 0, 1
"""
pass def __add__(self, y): # real signature unknown; restored from __doc__
""" 字符串拼接
x.__add__(y) <==> x+y """
pass def __contains__(self, y): # real signature unknown; restored from __doc__
""" 判断列表中是否包含某一项
x.__contains__(y) <==> y in x """
pass def __delitem__(self, y): # real signature unknown; restored from __doc__
"""删除列表中指定下标的项
x.__delitem__(y) <==> del x[y] """
pass def __delslice__(self, i, j): # real signature unknown; restored from __doc__
"""删除指定下标之间的内容,向下包含
x.__delslice__(i, j) <==> del x[i:j] Use of negative indices is not supported.
"""
pass def __eq__(self, y): # real signature unknown; restored from __doc__
""" 判断两个列表是否相等
x.__eq__(y) <==> x==y """
pass def __getattribute__(self, name): # real signature unknown; restored from __doc__
""" 无条件被调用,通过实例访问属性。
x.__getattribute__('name') <==> x.name """
pass def __getitem__(self, y): # real signature unknown; restored from __doc__
""" x.__getitem__(y) <==> x[y] """
pass def __getslice__(self, i, j): # real signature unknown; restored from __doc__
"""
x.__getslice__(i, j) <==> x[i:j] Use of negative indices is not supported.
"""
pass def __ge__(self, y): # real signature unknown; restored from __doc__
""" x.__ge__(y) <==> x>=y """
pass def __gt__(self, y): # real signature unknown; restored from __doc__
""" x.__gt__(y) <==> x>y """
pass def __iadd__(self, y): # real signature unknown; restored from __doc__
""" x.__iadd__(y) <==> x+=y """
pass def __imul__(self, y): # real signature unknown; restored from __doc__
"""
x.__imul__(y) <==> x*=y """
pass def __init__(self, seq=()): # known special case of list.__init__
"""
list() -> new empty list
list(iterable) -> new list initialized from iterable's items
# (copied from class doc)
"""
pass def __iter__(self): # real signature unknown; restored from __doc__
""" x.__iter__() <==> iter(x) """
pass def __len__(self): # real signature unknown; restored from __doc__
""" x.__len__() <==> len(x) """
pass def __le__(self, y): # real signature unknown; restored from __doc__
""" x.__le__(y) <==> x<=y """
pass def __lt__(self, y): # real signature unknown; restored from __doc__
""" x.__lt__(y) <==> x<y """
pass def __mul__(self, n): # real signature unknown; restored from __doc__
""" x.__mul__(n) <==> x*n """
pass @staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass def __ne__(self, y): # real signature unknown; restored from __doc__
""" x.__ne__(y) <==> x!=y """
pass def __repr__(self): # real signature unknown; restored from __doc__
""" x.__repr__() <==> repr(x) """
pass def __reversed__(self): # real signature unknown; restored from __doc__
""" L.__reversed__() -- return a reverse iterator over the list """
pass def __rmul__(self, n): # real signature unknown; restored from __doc__
""" x.__rmul__(n) <==> n*x """
pass def __setitem__(self, i, y): # real signature unknown; restored from __doc__
""" x.__setitem__(i, y) <==> x[i]=y """
pass def __setslice__(self, i, j, y): # real signature unknown; restored from __doc__
"""
x.__setslice__(i, j, y) <==> x[i:j]=y Use of negative indices is not supported.
"""
pass def __sizeof__(self): # real signature unknown; restored from __doc__
""" L.__sizeof__() -- size of L in memory, in bytes """
pass __hash__ = None list
list Code
接下来还是继续看一些list类中的常用方法:
(1)append:向列表中添加项
insert:在列表的指定位置加入值
extend:列表的扩展;那么列表可以自己扩展自己么???当然是可以的啦!
>>>
>>> a = [1,2,3,4]
>>> a.append(5)
>>> a
[1, 2, 3, 4, 5]
>>> b = [6,7]
>>> a.extend(b)
>>> a
[1, 2, 3, 4, 5, 6, 7]
>>> a.insert(2,0)
>>> a
[1, 2, 0, 3, 4, 5, 6, 7]
(2)index:返回列表中第一个匹配项的下标
__contain__:查看列表中是否包含某一项
count:查看列表中某一项出现的次数
>>> a
[1, 2, 0, 3, 4, 5, 6, 7]
>>> a.index(0)
2
>>> a.__contains__(7)
True
>>> a.__contains__(8)
False
>>> a.count(5)
1
(3)pop:删除并返回指定下标的值,默认为列表的最后一个值
remove:删除列表中与指定值匹配的第一个值
__delitem__:删除指定下标的值
__delslice__:删除指定下标区域内的所有值,下标向下包含
>>> a
[1, 2, 0, 3, 4, 5, 6, 7]
>>> a.pop()
7
>>> a
[1, 2, 0, 3, 4, 5, 6]
>>> a.pop(2)
0
>>> a
[1, 2, 3, 4, 5, 6]
>>> a.remove(2)
>>> a
[1, 3, 4, 5, 6]
>>> a.__delitem__(0)
>>> a
[3, 4, 5, 6]
>>> a.__delslice__(0,2)
>>> a
[5, 6]
(4)reverse:列表反转,这个反转并没有什么编码顺序,就是单纯的把原来的列表从头到尾调转过来而已。。。
sort:排序,数字、字符串按照ASCII,中文按照unicode从小到大排序。
>>> a = [5,4,6,8,2,6,9]
>>> a.sort()
>>> a
[2, 4, 5, 6, 6, 8, 9]
>>> a.reverse()
>>> a
[9, 8, 6, 6, 5, 4, 2]
Tuple类:
>>> dir(tuple)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']
tuple和list基本相同,但是tuple是不可修改的。所以也就没有添加,删除,修改等方法。但是count,__contain__等方法还是存在的,和list中用法相同,这里就不重复介绍了。
Dict类:
>>> dir(dict)
['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values', 'viewitems', 'viewkeys', 'viewvalues']
class dict(object):
"""
dict() -> new empty dictionary
dict(mapping) -> new dictionary initialized from a mapping object's
(key, value) pairs
dict(iterable) -> new dictionary initialized as if via:
d = {}
for k, v in iterable:
d[k] = v
dict(**kwargs) -> new dictionary initialized with the name=value pairs
in the keyword argument list. For example: dict(one=1, two=2)
""" def clear(self): # real signature unknown; restored from __doc__
""" 清除内容 """
""" D.clear() -> None. Remove all items from D. """
pass def copy(self): # real signature unknown; restored from __doc__
""" 浅拷贝 """
""" D.copy() -> a shallow copy of D """
pass @staticmethod # known case
def fromkeys(S, v=None): # real signature unknown; restored from __doc__
"""
dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v.
v defaults to None.
"""
pass def get(self, k, d=None): # real signature unknown; restored from __doc__
""" 根据key获取值,d是默认值 """
""" D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. """
pass def has_key(self, k): # real signature unknown; restored from __doc__
""" 是否有key """
""" D.has_key(k) -> True if D has a key k, else False """
return False def items(self): # real signature unknown; restored from __doc__
""" 所有项的列表形式 """
""" D.items() -> list of D's (key, value) pairs, as 2-tuples """
return [] def iteritems(self): # real signature unknown; restored from __doc__
""" 项可迭代 """
""" D.iteritems() -> an iterator over the (key, value) items of D """
pass def iterkeys(self): # real signature unknown; restored from __doc__
""" key可迭代 """
""" D.iterkeys() -> an iterator over the keys of D """
pass def itervalues(self): # real signature unknown; restored from __doc__
""" value可迭代 """
""" D.itervalues() -> an iterator over the values of D """
pass def keys(self): # real signature unknown; restored from __doc__
""" 所有的key列表 """
""" D.keys() -> list of D's keys """
return [] def pop(self, k, d=None): # real signature unknown; restored from __doc__
""" 获取并在字典中移除 """
"""
D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
If key is not found, d is returned if given, otherwise KeyError is raised
"""
pass def popitem(self): # real signature unknown; restored from __doc__
""" 获取并在字典中移除 """
"""
D.popitem() -> (k, v), remove and return some (key, value) pair as a
2-tuple; but raise KeyError if D is empty.
"""
pass def setdefault(self, k, d=None): # real signature unknown; restored from __doc__
""" 如果key不存在,则创建,如果存在,则返回已存在的值且不修改 """
""" D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """
pass def update(self, E=None, **F): # known special case of dict.update
""" 更新
{'name':'alex', 'age': 18000}
[('name','sbsbsb'),]
"""
"""
D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
If E present and has a .keys() method, does: for k in E: D[k] = E[k]
If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v
In either case, this is followed by: for k in F: D[k] = F[k]
"""
pass def values(self): # real signature unknown; restored from __doc__
""" 所有的值 """
""" D.values() -> list of D's values """
return [] def viewitems(self): # real signature unknown; restored from __doc__
""" 所有项,只是将内容保存至view对象中 """
""" D.viewitems() -> a set-like object providing a view on D's items """
pass def viewkeys(self): # real signature unknown; restored from __doc__
""" D.viewkeys() -> a set-like object providing a view on D's keys """
pass def viewvalues(self): # real signature unknown; restored from __doc__
""" D.viewvalues() -> an object providing a view on D's values """
pass def __cmp__(self, y): # real signature unknown; restored from __doc__
""" x.__cmp__(y) <==> cmp(x,y) """
pass def __contains__(self, k): # real signature unknown; restored from __doc__
""" D.__contains__(k) -> True if D has a key k, else False """
return False def __delitem__(self, y): # real signature unknown; restored from __doc__
""" x.__delitem__(y) <==> del x[y] """
pass def __eq__(self, y): # real signature unknown; restored from __doc__
""" x.__eq__(y) <==> x==y """
pass def __getattribute__(self, name): # real signature unknown; restored from __doc__
""" x.__getattribute__('name') <==> x.name """
pass def __getitem__(self, y): # real signature unknown; restored from __doc__
""" x.__getitem__(y) <==> x[y] """
pass def __ge__(self, y): # real signature unknown; restored from __doc__
""" x.__ge__(y) <==> x>=y """
pass def __gt__(self, y): # real signature unknown; restored from __doc__
""" x.__gt__(y) <==> x>y """
pass def __init__(self, seq=None, **kwargs): # known special case of dict.__init__
"""
dict() -> new empty dictionary
dict(mapping) -> new dictionary initialized from a mapping object's
(key, value) pairs
dict(iterable) -> new dictionary initialized as if via:
d = {}
for k, v in iterable:
d[k] = v
dict(**kwargs) -> new dictionary initialized with the name=value pairs
in the keyword argument list. For example: dict(one=1, two=2)
# (copied from class doc)
"""
pass def __iter__(self): # real signature unknown; restored from __doc__
""" x.__iter__() <==> iter(x) """
pass def __len__(self): # real signature unknown; restored from __doc__
""" x.__len__() <==> len(x) """
pass def __le__(self, y): # real signature unknown; restored from __doc__
""" x.__le__(y) <==> x<=y """
pass def __lt__(self, y): # real signature unknown; restored from __doc__
""" x.__lt__(y) <==> x<y """
pass @staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass def __ne__(self, y): # real signature unknown; restored from __doc__
""" x.__ne__(y) <==> x!=y """
pass def __repr__(self): # real signature unknown; restored from __doc__
""" x.__repr__() <==> repr(x) """
pass def __setitem__(self, i, y): # real signature unknown; restored from __doc__
""" x.__setitem__(i, y) <==> x[i]=y """
pass def __sizeof__(self): # real signature unknown; restored from __doc__
""" D.__sizeof__() -> size of D in memory, in bytes """
pass __hash__ = None dict
dict code
字典是python数据类型中的一大亮点,在其中占有着独特的地位,在这里先介绍一下字典的特性,和list不同,字典是无序的,它依靠key和value之间的联系进行索引,由于这种特殊的索引方式,字典中不可以有重复的key。
接下来还是就详细解析一些dict类中的常用方法:
(1)keys/values/items:取所有字典的key/取所有字典的value/取所有字典的key,value
>>> dic = {'name':'Eva','age':18}
>>> dic.keys()
['age', 'name']
>>> dic.values()
[18, 'Eva']
>>> dic.items()
[('age', 18), ('name', 'Eva')]
(2)已知key的情况下,获取value的值时可以使用‘字典名[key值]’的方法,在循环遍历中,尽管字典提供了for k,v in dic.items()的方法,但是为了避免占用内存空间,我们还是遍历key,再利用key的值就可以获取到value啦!
get:字典名[key值]的方式有一点弊端,那就是当key值不存在的时候会报错,这个时候我们使用get方法,可以避免报错的情况
>>> dic = {'name':'Eva','age':18}
>>> for n in dic:
print 'key:',n,'value:',dic[n] key: age value: 18
key: name value: Eva
>>> dic['name']
'Eva'
>>> dic['Gender'] Traceback (most recent call last):
File "<pyshell#384>", line 1, in <module>
dic['Gender']
KeyError: 'Gender'
>>> dic.get('name')
'Eva'
>>> dic.get('Gender')
>>>
(3)clear:清空字典
>>> dic = {'name':'Eva','age':18}
>>> dic.clear()
>>> dic
{}
(4)pop:根据指定的key删除一组数据
popitem:随机的删除一组数据。。。我觉得这就是python在逗我。。。
>>> dic
{'Gender': 'female', 'age': 18, 'name': 'Eva'}
>>> dic.popitem()
('Gender', 'female')
>>> dic.pop('age')
18
>>> dic
{'name': 'Eva'}
(5)setdefault:dic.setdefault[key1],key1存在,则返回value1,不存在,则自动创建value = 'None'
>>> dic
{'name': 'Eva'}
>>> dic.setdefault('name')
'Eva'
>>> dic.setdefault('age')
>>> dic
{'age': None, 'name': 'Eva'}
(6)update:dict1.update(dict2),判断dict2中的每一个key在dict1中是否存在,存在:就将dict1中的value更新成dict2中的,不存在:将key和value都复制过去
>>> dic
{'age': None, 'name': 'Eva'}
>>> dic1 = dic
>>>
>>> dic1
{'age': None, 'name': 'Eva'}
>>> dic2 = {'age': 18, 'name': 'Eva','gender':'female'}
>>> dic1.update(dic2)
>>> dic1
{'name': 'Eva', 'gender': 'female', 'age': 18}
(7)fromkeys:可以通过list创建一个字典,
dict.fromkeys([1,2,3],'test'),可以创建一个字典,但是如果a.fromkeys([1,2,3],[]},创建的字典的值都是一个空列表,那么其中一个列表的值发生了变化,所有的列表都会跟着发生变化,因为这个方法就是很傻很天真的把所有value的指针指向了同一个列表。所以感觉这个方法也是逗我玩儿的。。。
>>> a = dict.fromkeys([1,2,3],'test')
>>> a
{1: 'test', 2: 'test', 3: 'test'}
>>> a = dict.fromkeys([1,2,3],[])
>>> a[1].append('test')
>>> a
{1: ['test'], 2: ['test'], 3: ['test']}
(8)copy:dict字典里还自带了copy方法,但是这里的copy是浅拷贝,只copy字典的第一层内容。定义了dic字典,dic2是dic的copy,当我们修改dic的时候,我们就发现dic2特跟着贱贱的变了,这就是浅拷贝,只是浅浅的copy了一下,剩下的就直接把指针copy了,事实上还是指向了dic字典中的list地址。
>>> dic
{'name': 'Eva', 'otherInfo': {'hobby': ['sing', 'teaism']}, 'gender': 'female', 'age': 18}
>>> dic2 = dic.copy()
>>> dic2
{'gender': 'female', 'age': 18, 'name': 'Eva', 'otherInfo': {'hobby': ['sing', 'teaism']}}
>>> hobbylst = ['sing','teaism', 'tourism','jogging']
>>> dic
{'name': 'Eva', 'otherInfo': {'hobby': ['sing', 'teaism']}, 'gender': 'female', 'age': 18}
>>> dic2
{'gender': 'female', 'age': 18, 'name': 'Eva', 'otherInfo': {'hobby': ['sing', 'teaism']}}
python—基础类的那点儿所以然的更多相关文章
- 【Learning Python】【第二章】Python基础类型和基础操作
基础类型: 整型: py 3.0解决了整数溢出的问题,意味着整型不必考虑32位,64位,有无符号等问题,你写一个1亿亿亿,就是1亿亿亿,不会溢出 a = 10 ** 240 print(a) 执行以上 ...
- python基础类知识~pymysql封装类
一简介:咱们来介绍下 DBA常用的几个类 二 具体代码 #!/usr/bin/python3import pymysqlimport sysclass DBHelper: def __init__(s ...
- MyFirstDay(附6篇python亲历面试题)
一直以来都是在看别人写的内容,学习前辈们的经验,总感觉自己好像没有什么值得拿出来分享和交流的知识,最近在准备换工作(python后端开发),坐标上海,2019年3月,半个月面了6家(感觉效率是真不高. ...
- NodeJs编写小爬虫
一,爬虫及Robots协议 爬虫,是一种自动获取网页内容的程序.是搜索引擎的重要组成部分,因此搜索引擎优化很大程度上就是针对爬虫而做出的优化. robots.txt是一个文本文件,robots是一个协 ...
- MyFirstDay_答案_1.**猫(自己整理)
1>***猫: python基础类: 字符串反转的常用处理方式: # 方法一:使用字符串切片 s = "hello python" result = s[::-1] prin ...
- python的基础类源码解析——collection类
1.计数器(counter) Counter是对字典类型的补充,用于追踪值的出现次数. ps:具备字典的所有功能 + 自己的功能 ################################### ...
- Python人工智能之路 - 第一篇 : 你得会点儿Python基础
Python 号称是最接近人工智能的语言,因为它的动态便捷性和灵活的三方扩展,成就了它在人工智能领域的丰碑 走进Python,靠近人工智能 一.编程语言Python的基础 之 "浅入浅出&q ...
- protobuf基础类以及python 转换pb2.py文件
一 protobuf-前端解析js 前端解析思路: 1.问后端要数据模型文件,比如名为MODEL.proto 2.使用谷歌官方的工具生成MODEL.js 3.把项目中引用的MODEL.js 和谷歌官方 ...
- 饮水思源——python中常用基础类源码解析
1.bool类 2.int类 3.long类 4.float类 5.str类 6.list类 7.tuple类 8.dict类 9.collections类 Counter类:为hashable对象计 ...
随机推荐
- Unity3D 系统宏
Platform Defines The platform defines that Unity supports for your scripts are: Property: Functi ...
- Robot framework + appium环境搭建
Robot framework+appium环境搭建 首先梳理一下要用到的工具和安装包: 1. Android + JAVA. jdk : http://www.oracle.com/technetw ...
- jQ HTML之捕获 设置 元素添加与删除
捕获 设置修改 添加元素 删除元素
- 自定义宏把Word打造成全快捷键编辑器
自定义快捷键 折叠所有标题 Word选项—自定义功能区—自定义键盘—不在功能区内的命令—ColllapseAllHeadings 展开所有标题 Word选项—自定义功能区—自定义键盘—不在功能区内的命 ...
- SalesForce 入门
标签: Salesforce.com 一开始是一个云端的销售自动化(Sales Force Automation, SFA)以及客户关系管理工具(Customer Relationship Manag ...
- python:HTML + CSS 优先级 返回顶部
优先级 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8 ...
- 禁止输入中文 与 禁止输入数字在phonegap api环境效果
例子如下: <!doctype html> <html> <head> <meta charset="utf-8"> <tit ...
- 20160411002 经典SQL语句大全
一.基础 1.说明:创建数据库CREATE DATABASE database-name 2.说明:删除数据库drop database dbname3.说明:备份sql server--- 创建 备 ...
- html回忆(一)
1. 解决乱码,告诉浏览器 当前文档类型和编码 <meta http-equiv="Content-Type" content="text/html; charse ...
- 常用js总结1
1.cookie.js(封装了cookie的基本操作) 1.引入cookie.js <script type="text/javascript" src="../j ...