Python學(xué)習(xí)筆記
Day_09-曾經(jīng)的對象
Vamei:從最初的“Hello World!”噪窘,一路狂奔到對象面前,俗話說效扫,人生就像是一場旅行倔监,重要的是沿途的風(fēng)景。事實上荡短,前面幾張已經(jīng)多次出現(xiàn)對象丐枉,只不過,那時候沒有引入對象的概念掘托,現(xiàn)在讓我們回頭看看曾經(jīng)錯過的對象瘦锹。
9.1 列表對象
首先,讓我們定義一個列表a闪盔,使用type()獲取列表的類型弯院。
>>> a = [1, 2, 5, 2, 5]
>>> type(a)
輸出結(jié)果如下:
<class 'list'>
從返回結(jié)果可以看出,a屬于list類型泪掀,也就是列表類型听绳。而list是Python的內(nèi)置類,我們可以通過dir()和help()來進一步查看內(nèi)置類list的相關(guān)說明异赫。由于說明文件100多行椅挣,我進行了節(jié)減顯示。
>>> dir(list)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
>>> help(list)
Help on class list in module builtins:
class list(object)
| list(iterable=(), /)
|
| Built-in mutable sequence.
|
| If no argument is given, the constructor creates a new empty list.
| The argument must be an iterable if specified.
|
| Methods defined here:
|
| __add__(self, value, /)
| Return self+value.
|
| __contains__(self, key, /)
| Return key in self.
|
| __delitem__(self, key, /)
| Delete self[key]
|
| __getitem__(...)
| x.__getitem__(y) <==> x[y]
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| __iter__(self, /)
| Implement iter(self).
|
| __len__(self, /)
| Return len(self).
| __reversed__(self, /)
| Return a reverse iterator over the list.
|
| append(self, object, /)
| Append object to the end of the list.
|
| clear(self, /)
| Remove all items from list.
|
| copy(self, /)
| Return a shallow copy of the list.
|
| count(self, value, /)
| Return number of occurrences of value.
|
| extend(self, iterable, /)
| Extend list by appending elements from the iterable.
|
| index(self, value, start=0, stop=9223372036854775807, /)
| Return first index of value.
|
| Raises ValueError if the value is not present.
|
| insert(self, index, object, /)
| Insert object before index.
|
| pop(self, index=-1, /)
| Remove and return item at index (default last).
|
| Raises IndexError if list is empty or index is out of range.
|
| remove(self, value, /)
| Remove first occurrence of value.
|
| Raises ValueError if the value is not present.
|
| reverse(self, /)
| Reverse *IN PLACE*.
|
| sort(self, /, *, key=None, reverse=False)
| Sort the list in ascending order and return None.
|
| The sort is in-place (i.e. the list itself is modified) and stable (i.e. the
| order of two equal elements is maintained).
|
| If a key function is given, apply it once to each list item and sort them,
| ascending or descending, according to their function values.
|
| The reverse flag can be set to sort in descending order.
|
| ------------------------------------------------------- | Data and other attributes defined here:
|
| __hash__ = None
說明中列舉了list類中的屬性和方法塔拳。尤其是后面所羅列的list的一些方法鼠证。前面我學(xué)習(xí)list的知識的時候其實已經(jīng)都涉及到了,現(xiàn)在正好從對象的角度來重新認識靠抑,也相當于重新復(fù)習(xí)西下list的相關(guān)知識量九。
>>> a = [1, 3, 4, 8, 10.0, -11, True, False, "Hello"]
>>> a.count(3)
1
>>> a.index(4)
2
>>> a.append(6)
>>> a
[1, 3, 4, 8, 10.0, -11, True, False, 'Hello', 6]
>>> a.sort()
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
a.sort()
TypeError: '<' not supported between instances of 'str' and 'int'
>>> a.reverse()
>>> a
[6, 'Hello', 10.0, 8, 4, 3, True, 1, False, -11]
>>> a.pop()
-11
>>> a.remove(True)
>>> a
[6, 'Hello', 10.0, 8, 4, 3, 1, False]
>>> a.insert(3,4)
>>> a
[6, 'Hello', 10.0, 4, 8, 4, 3, 1, False]
>>> a.clear()
>>> a
[]
9.2 元組和字符串對象
前面的學(xué)習(xí)中我們知道,元組和字符串都屬于不可變的數(shù)據(jù)類型颂碧。
1荠列、元組
參考上面列表的做法,我們定義一個元組载城。
>>> a = (2, 7, 12)
>>> type(a) # <class 'tuple'>
通過查看dir()和help()肌似,我們可以看到tuple元組的屬性和方法。其中诉瓦,由于元組的不可變性锈嫩,其方法僅支持count和index兩種受楼。
Help on class tuple in module builtins:
class tuple(object)
| tuple(iterable=(), /)
|
| Built-in immutable sequence.
|
| If no argument is given, the constructor returns an empty tuple.
| If iterable is specified the tuple is initialized from iterable's items.
|
| If the argument is a tuple, the return value is the same object.
|
| Built-in subclasses:
| asyncgen_hooks
| UnraisableHookArgs
|
| Methods defined here:
|
| count(self, value, /)
| Return number of occurrences of value.
|
| index(self, value, start=0, stop=9223372036854775807, /)
| Return first index of value.
|
| Raises ValueError if the value is not present.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
因此,以定義好的元組a為例:
>>> a.count(7)
1
>>> a.index(12)
2
2呼寸、字符串
字符串雖然也是不可變的一種數(shù)據(jù)類型,我們定義的字符串也是屬于<class 'str'>
的一個對象猴贰。
但是我們通過查閱help(str)文件會發(fā)現(xiàn)对雪,有關(guān)字符串的方法確實非常之多。仔細查閱發(fā)現(xiàn)米绕,除了計數(shù)瑟捣、查找索引、判斷等的一些操作之外栅干,其余關(guān)于字符串的操作都是刪除原字符串然后再建立一個新的字符串迈套,邏輯上沒有違背不可變性。下面列舉幾個典型的字符串方法碱鳞。
>>> str = "Hello World"
>>> sub = "World"
>>> str.count(sub)
1
>>> str.find(sub)
6
>>> str.index(sub)
6
>>> str.isalnum()
False
>>> str.isalpha()
False
>>> str.isdigit()
False
>>> str.istitle()
True
>>> str.islower()
False
>>> str.isupper()
False
>>> str.lower()
'hello world'
>>> str.upper()
'HELLO WORLD'
>>> str
'Hello World'
通過例證發(fā)現(xiàn)桑李,前面的幾個是查詢索引和判斷的操作,后面兩種是將字符串的全部字母變成大寫或者小寫窿给。通過最后調(diào)用str發(fā)現(xiàn)贵白,原來的str字符串還是原來的,并未被改變崩泡。
9.3 詞典對象
詞典同樣屬于一個類禁荒,<class 'dict'>
。
通過help(dict)
可以看到角撞,詞典定義的方法不多呛伴,主要有以下幾種:
D.clear() #清空詞典所有元素,返回空詞典
D.copy() #復(fù)制一個詞典
D.get(key) #如果鍵存在谒所,返回值热康,如果不存在,返回None百炬。
D.items() #返回詞典中的元素褐隆,dict_item([(key1, value1), (key2, values), ...])
D.keys() #返回詞典中所有的key,dict_keys([key1, key2, key3...])
D.pop(key) #刪除對應(yīng)key及值剖踊,返回對應(yīng)key的值庶弃。
D.popitem() #刪除詞典最后一個key及對應(yīng)的value,返回這個key及對應(yīng)value組成的一個元組德澈。
D.setdefault(key, value) #向詞典中增加一組key及value歇攻,如果只有key,且這個key在詞典中不存在梆造,則在詞典中增加key:none
D.update() #
D.values() #返回詞典中所有的value缴守,dict_values([value1, value2...])
我們定義一個dict葬毫,然后使用一下上面的方法。
>>> dict1 = {"a":12, "b":20, "c":33 }
>>> dict1.clear()
>>> dict1
{}
>>> dict1 = {"a":12, "b":20, "c":33 }
>>> dict1.copy()
{'a': 12, 'b': 20, 'c': 33}
>>> dict1.get("a")
12
>>> dict1.get("d")
>>> dict1.items()
dict_items([('a', 12), ('b', 20), ('c', 33)])
>>> dict1.keys()
dict_keys(['a', 'b', 'c'])
>>> dict1.values()
dict_values([12, 20, 33])
>>> dict1.pop("b")
20
>>> dict1
{'a': 12, 'c': 33}
>>> dict1.popitem()
('c', 33)
>>> dict1 = {"a":12, "b":20, "c":33 }
>>> dict1.setdefault("d")
>>> dict1
{'a': 12, 'b': 20, 'c': 33, 'd': None}
>>> dict1.setdefault("d", 44)
>>>
>>> dict1
{'a': 12, 'b': 20, 'c': 33, 'd': None}
>>> dict1.setdefault("f", 55)
55
>>> dict1
{'a': 12, 'b': 20, 'c': 33, 'd': None, 'f': 55}
我們也可以通過詞典keys()方法循環(huán)遍歷每個元素的鍵屡穗,也可以通過values()方法遍歷每個元素的值贴捡。
>>> for i in dict1.keys():
print(i)
a
b
c
>>> for k in dict1.values():
print(k)
12
20
33