Python学习笔记-Day09

Python学习笔记

Day_09-曾经的对象

Vamei:从最初的“Hello World!”,一路狂奔到对象面前,俗话说,人生就像是一场旅行,重要的是沿途的风景。事实上,前面几张已经多次出现对象,只不过,那时候没有引入对象的概念,现在让我们回头看看曾经错过的对象。

9.1 列表对象

首先,让我们定义一个列表a,使用type()获取列表的类型。

>>> a = [1, 2, 5, 2, 5]
>>> type(a)

输出结果如下:

<class 'list'>

从返回结果可以看出,a属于list类型,也就是列表类型。而list是Python的内置类,我们可以通过dir()和help()来进一步查看内置类list的相关说明。由于说明文件100多行,我进行了节减显示。

>>> 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的一些方法。前面我学习list的知识的时候其实已经都涉及到了,现在正好从对象的角度来重新认识,也相当于重新复习西下list的相关知识。

>>> 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 元组和字符串对象

前面的学习中我们知道,元组和字符串都属于不可变的数据类型。

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、字符串

字符串虽然也是不可变的一种数据类型,我们定义的字符串也是属于<class 'str'>的一个对象。

但是我们通过查阅help(str)文件会发现,有关字符串的方法确实非常之多。仔细查阅发现,除了计数、查找索引、判断等的一些操作之外,其余关于字符串的操作都是删除原字符串然后再建立一个新的字符串,逻辑上没有违背不可变性。下面列举几个典型的字符串方法。

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

通过例证发现,前面的几个是查询索引和判断的操作,后面两种是将字符串的全部字母变成大写或者小写。通过最后调用str发现,原来的str字符串还是原来的,并未被改变。

9.3 词典对象

词典同样属于一个类,<class 'dict'>

通过help(dict)可以看到,词典定义的方法不多,主要有以下几种:

D.clear()  #清空词典所有元素,返回空词典
D.copy()  #复制一个词典
D.get(key)  #如果键存在,返回值,如果不存在,返回None。
D.items() #返回词典中的元素,dict_item([(key1, value1), (key2, values), ...])
D.keys() #返回词典中所有的key,dict_keys([key1, key2, key3...])
D.pop(key)  #删除对应key及值,返回对应key的值。
D.popitem() #删除词典最后一个key及对应的value,返回这个key及对应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()方法循环遍历每个元素的键,也可以通过values()方法遍历每个元素的值。

>>> for i in dict1.keys():
    print(i)

    
a
b
c

>>> for k in dict1.values():
    print(k)

    
12
20
33
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,711评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,932评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,770评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,799评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,697评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,069评论 1 276
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,535评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,200评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,353评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,290评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,331评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,020评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,610评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,694评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,927评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,330评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,904评论 2 341

推荐阅读更多精彩内容