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
View Code
 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.
View Code

  不要小看了上面的這些方法,它對於看一段新的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類:

  

1 >>> dir(long)
2 ['__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這樣的小數。

1 >>> dir(float)
2 ['__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類型。其余方法和整形並沒有太大差別,在這里也不做詳細總結了。

 1 >>> a  = 3.14
 2 >>> type(a)
 3 <type 'float'>
 4 >>> b = 6.28
 5 >>> c = b/a
 6 >>> print c,type(c)
 7 2.0 <type 'float'>
 8 >>> d = 8
 9 >>> type(d)
10 <type 'int'>
11 >>> d/c
12 4.0
13 >>> type(d/c)
14 <type 'float'>
View Code

  

  Str類:

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']

  

  1 class str(basestring):
  2     """
  3     str(object='') -> string
  4     
  5     Return a nice string representation of the object.
  6     If the argument is a string, the return value is the same object.
  7     """
  8     def capitalize(self):  
  9         """ 首字母變大寫 """
 10         """
 11         S.capitalize() -> string
 12         
 13         Return a copy of the string S with only its first character
 14         capitalized.
 15         """
 16         return ""
 17 
 18     def center(self, width, fillchar=None):  
 19         """ 內容居中,width:總長度;fillchar:空白處填充內容,默認無 """
 20         """
 21         S.center(width[, fillchar]) -> string
 22         
 23         Return S centered in a string of length width. Padding is
 24         done using the specified fill character (default is a space)
 25         """
 26         return ""
 27 
 28     def count(self, sub, start=None, end=None):  
 29         """ 子序列個數 """
 30         """
 31         S.count(sub[, start[, end]]) -> int
 32         
 33         Return the number of non-overlapping occurrences of substring sub in
 34         string S[start:end].  Optional arguments start and end are interpreted
 35         as in slice notation.
 36         """
 37         return 0
 38 
 39     def decode(self, encoding=None, errors=None):  
 40         """ 解碼 """
 41         """
 42         S.decode([encoding[,errors]]) -> object
 43         
 44         Decodes S using the codec registered for encoding. encoding defaults
 45         to the default encoding. errors may be given to set a different error
 46         handling scheme. Default is 'strict' meaning that encoding errors raise
 47         a UnicodeDecodeError. Other possible values are 'ignore' and 'replace'
 48         as well as any other name registered with codecs.register_error that is
 49         able to handle UnicodeDecodeErrors.
 50         """
 51         return object()
 52 
 53     def encode(self, encoding=None, errors=None):  
 54         """ 編碼,針對unicode """
 55         """
 56         S.encode([encoding[,errors]]) -> object
 57         
 58         Encodes S using the codec registered for encoding. encoding defaults
 59         to the default encoding. errors may be given to set a different error
 60         handling scheme. Default is 'strict' meaning that encoding errors raise
 61         a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
 62         'xmlcharrefreplace' as well as any other name registered with
 63         codecs.register_error that is able to handle UnicodeEncodeErrors.
 64         """
 65         return object()
 66 
 67     def endswith(self, suffix, start=None, end=None):  
 68         """ 是否以 xxx 結束 """
 69         """
 70         S.endswith(suffix[, start[, end]]) -> bool
 71         
 72         Return True if S ends with the specified suffix, False otherwise.
 73         With optional start, test S beginning at that position.
 74         With optional end, stop comparing S at that position.
 75         suffix can also be a tuple of strings to try.
 76         """
 77         return False
 78 
 79     def expandtabs(self, tabsize=None):  
 80         """ 將tab轉換成空格,默認一個tab轉換成8個空格 """
 81         """
 82         S.expandtabs([tabsize]) -> string
 83         
 84         Return a copy of S where all tab characters are expanded using spaces.
 85         If tabsize is not given, a tab size of 8 characters is assumed.
 86         """
 87         return ""
 88 
 89     def find(self, sub, start=None, end=None):  
 90         """ 尋找子序列位置,如果沒找到,則異常 """
 91         """
 92         S.find(sub [,start [,end]]) -> int
 93         
 94         Return the lowest index in S where substring sub is found,
 95         such that sub is contained within S[start:end].  Optional
 96         arguments start and end are interpreted as in slice notation.
 97         
 98         Return -1 on failure.
 99         """
100         return 0
101 
102     def format(*args, **kwargs): # known special case of str.format
103         """ 字符串格式化,動態參數,將函數式編程時細說 """
104         """
105         S.format(*args, **kwargs) -> string
106         
107         Return a formatted version of S, using substitutions from args and kwargs.
108         The substitutions are identified by braces ('{' and '}').
109         """
110         pass
111 
112     def index(self, sub, start=None, end=None):  
113         """ 子序列位置,如果沒找到,則返回-1  """
114         S.index(sub [,start [,end]]) -> int
115         
116         Like S.find() but raise ValueError when the substring is not found.
117         """
118         return 0
119 
120     def isalnum(self):  
121         """ 是否是字母和數字 """
122         """
123         S.isalnum() -> bool
124         
125         Return True if all characters in S are alphanumeric
126         and there is at least one character in S, False otherwise.
127         """
128         return False
129 
130     def isalpha(self):  
131         """ 是否是字母 """
132         """
133         S.isalpha() -> bool
134         
135         Return True if all characters in S are alphabetic
136         and there is at least one character in S, False otherwise.
137         """
138         return False
139 
140     def isdigit(self):  
141         """ 是否是數字 """
142         """
143         S.isdigit() -> bool
144         
145         Return True if all characters in S are digits
146         and there is at least one character in S, False otherwise.
147         """
148         return False
149 
150     def islower(self):  
151         """ 是否小寫 """
152         """
153         S.islower() -> bool
154         
155         Return True if all cased characters in S are lowercase and there is
156         at least one cased character in S, False otherwise.
157         """
158         return False
159 
160     def isspace(self):  
161         """是否空格
162         S.isspace() -> bool
163         
164         Return True if all characters in S are whitespace
165         and there is at least one character in S, False otherwise.
166         """
167         return False
168 
169     def istitle(self):  
170         """是否標題
171         S.istitle() -> bool
172         
173         Return True if S is a titlecased string and there is at least one
174         character in S, i.e. uppercase characters may only follow uncased
175         characters and lowercase characters only cased ones. Return False
176         otherwise.
177         """
178         return False
179 
180     def isupper(self):  
181         """是否大寫
182         S.isupper() -> bool
183         
184         Return True if all cased characters in S are uppercase and there is
185         at least one cased character in S, False otherwise.
186         """
187         return False
188 
189     def join(self, iterable):  
190         """ 連接 """
191         """
192         S.join(iterable) -> string
193         
194         Return a string which is the concatenation of the strings in the
195         iterable.  The separator between elements is S.
196         """
197         return ""
198 
199     def ljust(self, width, fillchar=None):  
200         """ 內容左對齊,右側填充 """
201         """
202         S.ljust(width[, fillchar]) -> string
203         
204         Return S left-justified in a string of length width. Padding is
205         done using the specified fill character (default is a space).
206         """
207         return ""
208 
209     def lower(self):  
210         """ 變小寫 """
211         """
212         S.lower() -> string
213         
214         Return a copy of the string S converted to lowercase.
215         """
216         return ""
217 
218     def lstrip(self, chars=None):  
219         """ 移除左側空白 """
220         """
221         S.lstrip([chars]) -> string or unicode
222         
223         Return a copy of the string S with leading whitespace removed.
224         If chars is given and not None, remove characters in chars instead.
225         If chars is unicode, S will be converted to unicode before stripping
226         """
227         return ""
228 
229     def partition(self, sep):  
230         """ 分割,前,中,后三部分 """
231         """
232         S.partition(sep) -> (head, sep, tail)
233         
234         Search for the separator sep in S, and return the part before it,
235         the separator itself, and the part after it.  If the separator is not
236         found, return S and two empty strings.
237         """
238         pass
239 
240     def replace(self, old, new, count=None):  
241         """ 替換 """
242         """
243         S.replace(old, new[, count]) -> string
244         
245         Return a copy of string S with all occurrences of substring
246         old replaced by new.  If the optional argument count is
247         given, only the first count occurrences are replaced.
248         """
249         return ""
250 
251     def rfind(self, sub, start=None, end=None):  
252         """
253         S.rfind(sub [,start [,end]]) -> int
254         
255         Return the highest index in S where substring sub is found,
256         such that sub is contained within S[start:end].  Optional
257         arguments start and end are interpreted as in slice notation.
258         
259         Return -1 on failure.
260         """
261         return 0
262 
263     def rindex(self, sub, start=None, end=None):  
264         """
265         S.rindex(sub [,start [,end]]) -> int
266         
267         Like S.rfind() but raise ValueError when the substring is not found.
268         """
269         return 0
270 
271     def rjust(self, width, fillchar=None):  
272         """
273         S.rjust(width[, fillchar]) -> string
274         
275         Return S right-justified in a string of length width. Padding is
276         done using the specified fill character (default is a space)
277         """
278         return ""
279 
280     def rpartition(self, sep):  
281         """
282         S.rpartition(sep) -> (head, sep, tail)
283         
284         Search for the separator sep in S, starting at the end of S, and return
285         the part before it, the separator itself, and the part after it.  If the
286         separator is not found, return two empty strings and S.
287         """
288         pass
289 
290     def rsplit(self, sep=None, maxsplit=None):  
291         """
292         S.rsplit([sep [,maxsplit]]) -> list of strings
293         
294         Return a list of the words in the string S, using sep as the
295         delimiter string, starting at the end of the string and working
296         to the front.  If maxsplit is given, at most maxsplit splits are
297         done. If sep is not specified or is None, any whitespace string
298         is a separator.
299         """
300         return []
301 
302     def rstrip(self, chars=None):  
303         """
304         S.rstrip([chars]) -> string or unicode
305         
306         Return a copy of the string S with trailing whitespace removed.
307         If chars is given and not None, remove characters in chars instead.
308         If chars is unicode, S will be converted to unicode before stripping
309         """
310         return ""
311 
312     def split(self, sep=None, maxsplit=None):  
313         """ 分割, maxsplit最多分割幾次 """
314         """
315         S.split([sep [,maxsplit]]) -> list of strings
316         
317         Return a list of the words in the string S, using sep as the
318         delimiter string.  If maxsplit is given, at most maxsplit
319         splits are done. If sep is not specified or is None, any
320         whitespace string is a separator and empty strings are removed
321         from the result.
322         """
323         return []
324 
325     def splitlines(self, keepends=False):  
326         """ 根據換行分割 """
327         """
328         S.splitlines(keepends=False) -> list of strings
329         
330         Return a list of the lines in S, breaking at line boundaries.
331         Line breaks are not included in the resulting list unless keepends
332         is given and true.
333         """
334         return []
335 
336     def startswith(self, prefix, start=None, end=None):  
337         """ 是否起始 """
338         """
339         S.startswith(prefix[, start[, end]]) -> bool
340         
341         Return True if S starts with the specified prefix, False otherwise.
342         With optional start, test S beginning at that position.
343         With optional end, stop comparing S at that position.
344         prefix can also be a tuple of strings to try.
345         """
346         return False
347 
348     def strip(self, chars=None):  
349         """ 移除兩段空白 """
350         """
351         S.strip([chars]) -> string or unicode
352         
353         Return a copy of the string S with leading and trailing
354         whitespace removed.
355         If chars is given and not None, remove characters in chars instead.
356         If chars is unicode, S will be converted to unicode before stripping
357         """
358         return ""
359 
360     def swapcase(self):  
361         """ 大寫變小寫,小寫變大寫 """
362         """
363         S.swapcase() -> string
364         
365         Return a copy of the string S with uppercase characters
366         converted to lowercase and vice versa.
367         """
368         return ""
369 
370     def title(self):  
371         """
372         S.title() -> string
373         
374         Return a titlecased version of S, i.e. words start with uppercase
375         characters, all remaining cased characters have lowercase.
376         """
377         return ""
378 
379     def translate(self, table, deletechars=None):  
380         """
381         轉換,需要先做一個對應表,最后一個表示刪除字符集合
382         intab = "aeiou"
383         outtab = "12345"
384         trantab = maketrans(intab, outtab)
385         str = "this is string example....wow!!!"
386         print str.translate(trantab, 'xm')
387         """
388 
389         """
390         S.translate(table [,deletechars]) -> string
391         
392         Return a copy of the string S, where all characters occurring
393         in the optional argument deletechars are removed, and the
394         remaining characters have been mapped through the given
395         translation table, which must be a string of length 256 or None.
396         If the table argument is None, no translation is applied and
397         the operation simply removes the characters in deletechars.
398         """
399         return ""
400 
401     def upper(self):  
402         """
403         S.upper() -> string
404         
405         Return a copy of the string S converted to uppercase.
406         """
407         return ""
408 
409     def zfill(self, width):  
410         """方法返回指定長度的字符串,原字符串右對齊,前面填充0。"""
411         """
412         S.zfill(width) -> string
413         
414         Pad a numeric string S with zeros on the left, to fill a field
415         of the specified width.  The string S is never truncated.
416         """
417         return ""
418 
419     def _formatter_field_name_split(self, *args, **kwargs): # real signature unknown
420         pass
421 
422     def _formatter_parser(self, *args, **kwargs): # real signature unknown
423         pass
424 
425     def __add__(self, y):  
426         """ x.__add__(y) <==> x+y """
427         pass
428 
429     def __contains__(self, y):  
430         """ x.__contains__(y) <==> y in x """
431         pass
432 
433     def __eq__(self, y):  
434         """ x.__eq__(y) <==> x==y """
435         pass
436 
437     def __format__(self, format_spec):  
438         """
439         S.__format__(format_spec) -> string
440         
441         Return a formatted version of S as described by format_spec.
442         """
443         return ""
444 
445     def __getattribute__(self, name):  
446         """ x.__getattribute__('name') <==> x.name """
447         pass
448 
449     def __getitem__(self, y):  
450         """ x.__getitem__(y) <==> x[y] """
451         pass
452 
453     def __getnewargs__(self, *args, **kwargs): # real signature unknown
454         pass
455 
456     def __getslice__(self, i, j):  
457         """
458         x.__getslice__(i, j) <==> x[i:j]
459                    
460                    Use of negative indices is not supported.
461         """
462         pass
463 
464     def __ge__(self, y):  
465         """ x.__ge__(y) <==> x>=y """
466         pass
467 
468     def __gt__(self, y):  
469         """ x.__gt__(y) <==> x>y """
470         pass
471 
472     def __hash__(self):  
473         """ x.__hash__() <==> hash(x) """
474         pass
475 
476     def __init__(self, string=''): # known special case of str.__init__
477         """
478         str(object='') -> string
479         
480         Return a nice string representation of the object.
481         If the argument is a string, the return value is the same object.
482         # (copied from class doc)
483         """
484         pass
485 
486     def __len__(self):  
487         """ x.__len__() <==> len(x) """
488         pass
489 
490     def __le__(self, y):  
491         """ x.__le__(y) <==> x<=y """
492         pass
493 
494     def __lt__(self, y):  
495         """ x.__lt__(y) <==> x<y """
496         pass
497 
498     def __mod__(self, y):  
499         """ x.__mod__(y) <==> x%y """
500         pass
501 
502     def __mul__(self, n):  
503         """ x.__mul__(n) <==> x*n """
504         pass
505 
506     @staticmethod # known case of __new__
507     def __new__(S, *more):  
508         """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
509         pass
510 
511     def __ne__(self, y):  
512         """ x.__ne__(y) <==> x!=y """
513         pass
514 
515     def __repr__(self):  
516         """ x.__repr__() <==> repr(x) """
517         pass
518 
519     def __rmod__(self, y):  
520         """ x.__rmod__(y) <==> y%x """
521         pass
522 
523     def __rmul__(self, n):  
524         """ x.__rmul__(n) <==> n*x """
525         pass
526 
527     def __sizeof__(self):  
528         """ S.__sizeof__() -> size of S in memory, in bytes """
529         pass
530 
531     def __str__(self):  
532         """ x.__str__() <==> str(x) """
533         pass
534 
535 str
str Code

  接下來對於str類中一些常用的方法進行說明:

   (1)capitalize:將首字母大寫

1 >>> name = 'eva'
2 >>> name.capitalize()
3 'Eva'

  (2)center/ljust/rjst:固定字符串長度,居中/居左/居右 ,下面是使用示例,當然沒有正常人會上來就這么用,一般用在打印列表和字典的時候整理格式。

1 >>> str1.ljust(20,)         #設置格式左對齊,其余部分默認情況下,以空格填充
2 'hello,Eva!          '
3 >>> str1.center(20,'*')   #設置格式左對齊,剩余部分已“*”填充
4 '*****hello,Eva!*****'
5 >>> str1.rjust(20,'&')    #設置格式左對齊,剩余部分已“&”填充
6 '&&&&&&&&&&hello,Eva!'

  

   (3)count:子序列個數,用來統計一個字符串中包含指定子序列的個數。這個子序列可以是一個字符,也可以是多個字符~~

1 >>> str1 = 'hello,Eva.Have a nice day'
2 >>> str1.count('a')
3 4
4 >>> str1.count('va')
5 1

   (4)encode/decode:編碼/解碼,如下左圖,各個編碼之間是不能直接轉換的,計算機內存中默認存儲的編碼格式是unicode,所以當我們需要將編碼在utf8和gbk之間轉換的時候,都需要和unicode做操作。
       我的終端編碼是gbk編碼的,當我創建一個string = '景'時,string就被存儲成gbk格式。此時我想把gbk格式轉換成utf8格式,就要先將原gbk格式的string轉換成unicode格式,然后再將unicode轉換成utf8格式。如下右圖,老師說,把這個字整亂碼了我們的目的就達到了,哈~

             

   (5)endswith:是否以...(子串)結尾。這里的子串依然可以是一個或多個字符。

1 >>> str1 = 'hello,Eva.Have a nice day'
2 >>> str1.endswith('day')
3 True

   (6)expandtabs:將tab轉換成空格,默認一個tab轉換成8個空格。當然這里也可以自行指定轉換成多少個空格,要不是怕寫不下,我就指定它轉成千八百個。。。

1 >>> name = '    Eva'
2 >>> name.expandtabs()
3 '        Eva'
4 >>> name.expandtabs(20)
5 '                    Eva'

   (7)find:返回字符串中第一個子序列的下標。

      rfind:和find用法一樣,只是它是從右向左查找

          index:和find的左右一致,只是find找不到的時候會返回-1,而index找不到的時候會報錯

      值得注意的是,當我們在一個字符串中查找某一個子序列的時候,如果這個字符串中含有多個子序列,只會返回第一個找到的下標,不會返回其他的。

 1 >>> name  = 'hello,eva,how are you'
 2 >>> name.find('o')
 3 4
 4 >>> name.find('t')
 5 -1
 6 >>> name.index('e')
 7 1
 8 >>> name.index('t')
 9 
10 Traceback (most recent call last):
11   File "<pyshell#234>", line 1, in <module>
12     name.index('t')
13 ValueError: substring not found

   (8)format:各種格式化,動態參數。

 1 >>> str1 = 'I\'m {0},age {1}'
 2 >>> str2 = 'I\'m {name},age {age}'
 3 >>> lst = ['Eva','18']
 4 >>> dic = {'name':'Eva','age':'18'}
 5 >>> str1.format('Eva','18')
 6 "I'm Eva,age 18"
 7 >>> str1.format(*lst)
 8 "I'm Eva,age 18"
 9 >>> str2.format(age = '18',name = 'Eva')
10 "I'm Eva,age 18"
11 >>> str2.format(**dic)
12 "I'm Eva,age 18"

   (9)isalnum/isalpha/isdigit/isspace/islower/istitle/isupper:是否是字母或數字/是否字母/是否數字/是否空格/是否小寫/是否標題/是否全大寫,總之都是一些判斷的方法,返回的不是True就是False。。。

   (10)partition/split:這兩個方法都用來分割。

  partition會將指定的子串串提取並將子串兩側內容分割,只匹配一次,並返回元祖;

  split會根據指定子串,將整個字符串所有匹配的子串匹配到並剔除,將其他內容分割,返回數組。

1 >>> food = 'apple,banana,chocolate'
2 >>> food.split(',')
3 ['apple', 'banana', 'chocolate']
4 >>> food.partition(',')
5 ('apple', ',', 'banana,chocolate')

   (11)replace:替換。會替換字符串中所有符合條件的子串。。。原諒我的chinglish。。。

1 >>> str1 = 'I\'m Rita,Do you remember,Rita?'
2 >>> str1.replace('Rita','Eva')
3 "I'm Eva,Do you remember,Eva?"

   (12)swapcase:大寫變小寫,小寫變大寫

1 >>> str1 = 'I\'m Eva'
2 >>> str1.swapcase()
3 "i'M eVA"

   (13)translate:替換,刪除字符串。這個方法的使用比較麻煩,在使用前需要引入string類,並調用其中的maketrans方法建立映射關系。這樣,在translate方法中,加入映射參數,就可以看到效果了。如下‘aeiou’分別和‘12345’建立了映射關系,於是在最后,aeiou都被12345相應的替換掉了,translate第二個參數是刪除,它刪除了所有的‘.’

1 >>> in_tab = 'aeiou'
2 >>> out_tab = '12345'
3 >>> import string
4 >>> transtab = string.maketrans(in_tab,out_tab)
5 >>> str = 'this is a translate example...wow!'
6 >>> str1 = 'this is a translate example...wow!'
7 >>> print str1.translate(transtab,'..')
8 th3s 3s 1 tr1nsl1t2 2x1mpl2w4w!

  

  List類:

1 >>> dir(list)
2 ['__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']

 

  1 class list(object):
  2     """
  3     list() -> new empty list
  4     list(iterable) -> new list initialized from iterable's items
  5     """在數組的末尾新增一項
  6     def append(self, p_object): # real signature unknown; restored from __doc__
  7         """
  8         L.append(object) -- append object to end """
  9         pass
 10 
 11     def count(self, value): # real signature unknown; restored from __doc__
 12         """ 查看lst中某一項出現的次數
 13         L.count(value) -> integer -- return number of occurrences of value """
 14         return 0
 15 
 16     def extend(self, iterable): # real signature unknown; restored from __doc__
 17         """將原列表與其他列表擴展成新列表
 18         L.extend(iterable) -- extend list by appending elements from the iterable """
 19         pass
 20 
 21     def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
 22         """返回列表中第一個匹配項的下標,找不到會報錯
 23         L.index(value, [start, [stop]]) -> integer -- return first index of value.
 24         Raises ValueError if the value is not present.
 25         """
 26         return 0
 27 
 28     def insert(self, index, p_object): # real signature unknown; restored from __doc__
 29         """在指定位置插入項
 30         L.insert(index, object) -- insert object before index """
 31         pass
 32 
 33     def pop(self, index=None): # real signature unknown; restored from __doc__
 34         """返回指定位置的值,並將其從列表中刪除。默認對末尾項操作
 35         L.pop([index]) -> item -- remove and return item at index (default last).
 36         Raises IndexError if list is empty or index is out of range.
 37         """
 38         pass
 39 
 40     def remove(self, value): # real signature unknown; restored from __doc__
 41         """從列表中移除第一個符合與指定值相等的項
 42         L.remove(value) -- remove first occurrence of value.
 43         Raises ValueError if the value is not present.
 44         """
 45         pass
 46 
 47     def reverse(self): # real signature unknown; restored from __doc__
 48         """列表反轉
 49         L.reverse() -- reverse *IN PLACE* """
 50         pass
 51 
 52     def sort(self, cmp=None, key=None, reverse=False): # real signature unknown; restored from __doc__
 53         """排序,數字、字符串按照ASCII,中文按照unicode從小到大排序。
 54         L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
 55         cmp(x, y) -> -1, 0, 1
 56         """
 57         pass
 58 
 59     def __add__(self, y): # real signature unknown; restored from __doc__
 60         """ 字符串拼接
 61         x.__add__(y) <==> x+y """
 62         pass
 63 
 64     def __contains__(self, y): # real signature unknown; restored from __doc__
 65         """ 判斷列表中是否包含某一項
 66         x.__contains__(y) <==> y in x """
 67         pass
 68 
 69     def __delitem__(self, y): # real signature unknown; restored from __doc__
 70         """刪除列表中指定下標的項
 71         x.__delitem__(y) <==> del x[y] """
 72         pass
 73 
 74     def __delslice__(self, i, j): # real signature unknown; restored from __doc__
 75         """刪除指定下標之間的內容,向下包含
 76         x.__delslice__(i, j) <==> del x[i:j]
 77                    
 78                    Use of negative indices is not supported.
 79         """
 80         pass
 81 
 82     def __eq__(self, y): # real signature unknown; restored from __doc__
 83         """ 判斷兩個列表是否相等
 84         x.__eq__(y) <==> x==y """
 85         pass
 86 
 87     def __getattribute__(self, name): # real signature unknown; restored from __doc__
 88         """ 無條件被調用,通過實例訪問屬性。
 89         x.__getattribute__('name') <==> x.name """
 90         pass
 91 
 92     def __getitem__(self, y): # real signature unknown; restored from __doc__
 93         """ x.__getitem__(y) <==> x[y] """
 94         pass
 95 
 96     def __getslice__(self, i, j): # real signature unknown; restored from __doc__
 97         """
 98         x.__getslice__(i, j) <==> x[i:j]
 99                    
100                    Use of negative indices is not supported.
101         """
102         pass
103 
104     def __ge__(self, y): # real signature unknown; restored from __doc__
105         """ x.__ge__(y) <==> x>=y """
106         pass
107 
108     def __gt__(self, y): # real signature unknown; restored from __doc__
109         """ x.__gt__(y) <==> x>y """
110         pass
111 
112     def __iadd__(self, y): # real signature unknown; restored from __doc__
113         """ x.__iadd__(y) <==> x+=y """
114         pass
115 
116     def __imul__(self, y): # real signature unknown; restored from __doc__
117         """ 
118         x.__imul__(y) <==> x*=y """
119         pass
120 
121     def __init__(self, seq=()): # known special case of list.__init__
122         """
123         list() -> new empty list
124         list(iterable) -> new list initialized from iterable's items
125         # (copied from class doc)
126         """
127         pass
128 
129     def __iter__(self): # real signature unknown; restored from __doc__
130         """ x.__iter__() <==> iter(x) """
131         pass
132 
133     def __len__(self): # real signature unknown; restored from __doc__
134         """ x.__len__() <==> len(x) """
135         pass
136 
137     def __le__(self, y): # real signature unknown; restored from __doc__
138         """ x.__le__(y) <==> x<=y """
139         pass
140 
141     def __lt__(self, y): # real signature unknown; restored from __doc__
142         """ x.__lt__(y) <==> x<y """
143         pass
144 
145     def __mul__(self, n): # real signature unknown; restored from __doc__
146         """ x.__mul__(n) <==> x*n """
147         pass
148 
149     @staticmethod # known case of __new__
150     def __new__(S, *more): # real signature unknown; restored from __doc__
151         """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
152         pass
153 
154     def __ne__(self, y): # real signature unknown; restored from __doc__
155         """ x.__ne__(y) <==> x!=y """
156         pass
157 
158     def __repr__(self): # real signature unknown; restored from __doc__
159         """ x.__repr__() <==> repr(x) """
160         pass
161 
162     def __reversed__(self): # real signature unknown; restored from __doc__
163         """ L.__reversed__() -- return a reverse iterator over the list """
164         pass
165 
166     def __rmul__(self, n): # real signature unknown; restored from __doc__
167         """ x.__rmul__(n) <==> n*x """
168         pass
169 
170     def __setitem__(self, i, y): # real signature unknown; restored from __doc__
171         """ x.__setitem__(i, y) <==> x[i]=y """
172         pass
173 
174     def __setslice__(self, i, j, y): # real signature unknown; restored from __doc__
175         """
176         x.__setslice__(i, j, y) <==> x[i:j]=y
177                    
178                    Use  of negative indices is not supported.
179         """
180         pass
181 
182     def __sizeof__(self): # real signature unknown; restored from __doc__
183         """ L.__sizeof__() -- size of L in memory, in bytes """
184         pass
185 
186     __hash__ = None
187 
188 list         
list Code

  接下來還是繼續看一些list類中的常用方法:

  
   (1)append:向列表中添加項

       insert:在列表的指定位置加入值

     extend:列表的擴展;那么列表可以自己擴展自己么???當然是可以的啦!

 1 >>> 
 2 >>> a = [1,2,3,4]
 3 >>> a.append(5)
 4 >>> a
 5 [1, 2, 3, 4, 5]
 6 >>> b = [6,7]
 7 >>> a.extend(b)
 8 >>> a
 9 [1, 2, 3, 4, 5, 6, 7]
10 >>> a.insert(2,0)
11 >>> a
12 [1, 2, 0, 3, 4, 5, 6, 7]

    (2)index:返回列表中第一個匹配項的下標

           __contain__:查看列表中是否包含某一項

       count:查看列表中某一項出現的次數

 1 >>> a
 2 [1, 2, 0, 3, 4, 5, 6, 7]
 3 >>> a.index(0)
 4 2
 5 >>> a.__contains__(7)
 6 True
 7 >>> a.__contains__(8)
 8 False
 9 >>> a.count(5)
10 1

    (3)pop:刪除並返回指定下標的值,默認為列表的最后一個值

       remove:刪除列表中與指定值匹配的第一個值

                  __delitem__:刪除指定下標的值

      __delslice__:刪除指定下標區域內的所有值,下標向下包含

 1 >>> a
 2 [1, 2, 0, 3, 4, 5, 6, 7]
 3 >>> a.pop()
 4 7
 5 >>> a
 6 [1, 2, 0, 3, 4, 5, 6]
 7 >>> a.pop(2)
 8 0
 9 >>> a
10 [1, 2, 3, 4, 5, 6]
11 >>> a.remove(2)
12 >>> a
13 [1, 3, 4, 5, 6]
14 >>> a.__delitem__(0)
15 >>> a
16 [3, 4, 5, 6]
17 >>> a.__delslice__(0,2)
18 >>> a
19 [5, 6]

     (4)reverse:列表反轉,這個反轉並沒有什么編碼順序,就是單純的把原來的列表從頭到尾調轉過來而已。。。
         sort:排序,數字、字符串按照ASCII,中文按照unicode從小到大排序。

1 >>> a = [5,4,6,8,2,6,9]
2 >>> a.sort()
3 >>> a
4 [2, 4, 5, 6, 6, 8, 9]
5 >>> a.reverse()
6 >>> a
7 [9, 8, 6, 6, 5, 4, 2]

  Tuple類:

1 >>> dir(tuple)
2 ['__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類:

1 >>> dir(dict)
2 ['__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

    

1 >>> dic = {'name':'Eva','age':18}
2 >>> dic.keys()
3 ['age', 'name']
4 >>> dic.values()
5 [18, 'Eva']
6 >>> dic.items()
7 [('age', 18), ('name', 'Eva')]

    (2)已知key的情況下,獲取value的值時可以使用‘字典名[key值]’的方法,在循環遍歷中,盡管字典提供了for k,v in dic.items()的方法,但是為了避免占用內存空間,我們還是遍歷key,再利用key的值就可以獲取到value啦!

    get:字典名[key值]的方式有一點弊端,那就是當key值不存在的時候會報錯,這個時候我們使用get方法,可以避免報錯的情況

 1 >>> dic = {'name':'Eva','age':18}
 2 >>> for n in dic:
 3     print 'key:',n,'value:',dic[n]
 4 
 5     
 6 key: age value: 18
 7 key: name value: Eva
 8 >>> dic['name']
 9 'Eva'
10 >>> dic['Gender']
11 
12 Traceback (most recent call last):
13   File "<pyshell#384>", line 1, in <module>
14     dic['Gender']
15 KeyError: 'Gender'
16 >>> dic.get('name')
17 'Eva'
18 >>> dic.get('Gender')
19 >>> 

     (3)clear:清空字典

1 >>> dic = {'name':'Eva','age':18}
2 >>> dic.clear()
3 >>> dic
4 {}

    (4)pop:根據指定的key刪除一組數據

        popitem:隨機的刪除一組數據。。。我覺得這就是python在逗我。。。

1 >>> dic
2 {'Gender': 'female', 'age': 18, 'name': 'Eva'}
3 >>> dic.popitem()
4 ('Gender', 'female')
5 >>> dic.pop('age')
6 18
7 >>> dic
8 {'name': 'Eva'}

    (5)setdefault:dic.setdefault[key1],key1存在,則返回value1,不存在,則自動創建value = 'None'

1 >>> dic
2 {'name': 'Eva'}
3 >>> dic.setdefault('name')
4 'Eva'
5 >>> dic.setdefault('age')
6 >>> dic
7 {'age': None, 'name': 'Eva'}

    (6)update:dict1.update(dict2),判斷dict2中的每一個key在dict1中是否存在,存在:就將dict1中的value更新成dict2中的,不存在:將key和value都復制過去

 1 >>> dic
 2 {'age': None, 'name': 'Eva'}
 3 >>> dic1 = dic
 4 >>> 
 5 >>> dic1
 6 {'age': None, 'name': 'Eva'}
 7 >>> dic2 = {'age': 18, 'name': 'Eva','gender':'female'}
 8 >>> dic1.update(dic2)
 9 >>> dic1
10 {'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地址。

 1 >>> dic
 2 {'name': 'Eva', 'otherInfo': {'hobby': ['sing', 'teaism']}, 'gender': 'female', 'age': 18}
 3 >>> dic2 = dic.copy()
 4 >>> dic2
 5 {'gender': 'female', 'age': 18, 'name': 'Eva', 'otherInfo': {'hobby': ['sing', 'teaism']}}
 6 >>> hobbylst = ['sing','teaism', 'tourism','jogging']
 7 >>> dic
 8 {'name': 'Eva', 'otherInfo': {'hobby': ['sing', 'teaism']}, 'gender': 'female', 'age': 18}
 9 >>> dic2
10 {'gender': 'female', 'age': 18, 'name': 'Eva', 'otherInfo': {'hobby': ['sing', 'teaism']}}

 

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM