Object Oriented Python 简明教程

Object Oriented Python - Data Structures

从语法角度来看,Python 数据结构非常直观,它们提供大量操作选择。您需要根据数据的内容、是否需要修改数据、数据是否固定以及需要什么访问类型(例如,开始/结束/随机等)来选择 Python 数据结构。

Lists

在 Python 中,列表代表最通用的数据结构类型。列表是一个容器,它在方括号中保存逗号分隔的值(项或元素)。当我们需要使用多个相关值时,列表会非常有用。由于列表将数据保存在一起,我们可以一次对多个值执行相同的方法和操作。列表索引从零开始,与字符串不同,列表是可变的。

Data Structure - List

>>>
>>> # Any Empty List
>>> empty_list = []
>>>
>>> # A list of String
>>> str_list = ['Life', 'Is', 'Beautiful']
>>> # A list of Integers
>>> int_list = [1, 4, 5, 9, 18]
>>>
>>> #Mixed items list
>>> mixed_list = ['This', 9, 'is', 18, 45.9, 'a', 54, 'mixed', 99, 'list']
>>> # To print the list
>>>
>>> print(empty_list)
[]
>>> print(str_list)
['Life', 'Is', 'Beautiful']
>>> print(type(str_list))
<class 'list'>
>>> print(int_list)
[1, 4, 5, 9, 18]
>>> print(mixed_list)
['This', 9, 'is', 18, 45.9, 'a', 54, 'mixed', 99, 'list']

Accessing Items in Python List

列表的每个项都分配了一个数字,即该数字的索引或位置。索引始终从零开始,第二个索引为一,依此类推。要访问列表中的项,我们可以在方括号内使用这些索引号。例如,观察以下代码:

>>> mixed_list = ['This', 9, 'is', 18, 45.9, 'a', 54, 'mixed', 99, 'list']
>>>
>>> # To access the First Item of the list
>>> mixed_list[0]
'This'
>>> # To access the 4th item
>>> mixed_list[3]
18
>>> # To access the last item of the list
>>> mixed_list[-1]
'list'

Empty Objects

空对象是最简单、最基本的 Python 内置类型。我们已经多次在不知不觉中使用它们,并且已将它们扩展到我们创建的每个类。编写空类的主要目的是暂时阻止某些内容,并在稍后对其进行扩展并添加行为。

向类添加行为意味着用一个对象替换一个数据结构,并更改对它的所有引用。所以在创建任何内容之前,检查数据是否伪装成一个对象非常重要。观察以下代码以增强理解:

>>> #Empty objects
>>>
>>> obj = object()
>>> obj.x = 9
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
obj.x = 9
AttributeError: 'object' object has no attribute 'x'

因此,从上面我们可以看出,不可能对直接实例化的对象设置任何属性。当 Python 允许一个对象拥有任意属性时,它会占用一定数量的系统内存来跟踪每个对象具有的属性,以便同时存储属性名称和属性值。即使没有存储任何属性,也会为潜在的新属性分配一定数量的内存。

所以,Python 默认情况下禁用对象和其他几个内置对象的任意属性。

>>> # Empty Objects
>>>
>>> class EmpObject:
    pass
>>> obj = EmpObject()
>>> obj.x = 'Hello, World!'
>>> obj.x
'Hello, World!'

因此,如果我们要将属性分组在一起,我们可以将它们存储在一个空对象中,如上所示的代码中。但是,并不总是建议使用此方法。请记住,只有当您想要同时指定数据和行为时,才应该使用类和对象。

Tuples

元组与列表类似,可存储元素。但是,它们是不可变的,所以我们无法添加、删除或替换对象。元组提供的不可变性的主要好处是我们可以将其用作字典的键,或在对象需要哈希值的其他位置。

元组用于存储数据,而不是行为。如果您需要行为来操作元组,则需要将元组传递给执行操作的函数(或另一个对象上的方法)。

由于元组可以作为字典键,因此存储的值彼此不同。我们可以通过用逗号分隔值来创建元组。元组用括号括住,但不是强制的。以下代码显示了两个相同的赋值。

>>> stock1 = 'MSFT', 95.00, 97.45, 92.45
>>> stock2 = ('MSFT', 95.00, 97.45, 92.45)
>>> type (stock1)
<class 'tuple'>
>>> type(stock2)
<class 'tuple'>
>>> stock1 == stock2
True
>>>

Defining a Tuple

元组与列表非常相似,除了整套元素用括号括住而不是用方括号括住。

就像切片列表时,你会得到一个新列表,切片元组时,你会得到一个新元组。

>>> tupl = ('Tuple','is', 'an','IMMUTABLE', 'list')
>>> tupl
('Tuple', 'is', 'an', 'IMMUTABLE', 'list')
>>> tupl[0]
'Tuple'
>>> tupl[-1]
'list'
>>> tupl[1:3]
('is', 'an')

Python Tuple Methods

以下代码显示了 Python 元组中的方法:

>>> tupl
('Tuple', 'is', 'an', 'IMMUTABLE', 'list')
>>> tupl.append('new')
Traceback (most recent call last):
   File "<pyshell#148>", line 1, in <module>
      tupl.append('new')
AttributeError: 'tuple' object has no attribute 'append'
>>> tupl.remove('is')
Traceback (most recent call last):
   File "<pyshell#149>", line 1, in <module>
      tupl.remove('is')
AttributeError: 'tuple' object has no attribute 'remove'
>>> tupl.index('list')
4
>>> tupl.index('new')
Traceback (most recent call last):
   File "<pyshell#151>", line 1, in <module>
      tupl.index('new')
ValueError: tuple.index(x): x not in tuple
>>> "is" in tupl
True
>>> tupl.count('is')
1

从上面显示的代码中,我们可以理解元组是不可变的,因此:

  1. cannot 添加元素到元组。

  2. cannot 追加或扩展一个方法。

  3. cannot 从元组中删除元素。

  4. 元组有 no 删除或弹出方法。

  5. 计数和索引是元组中的可用方法。

Dictionary

字典是 Python 的内置数据类型之一,它定义了键和值之间的一对一关系。

Defining Dictionaries

观察以下代码以了解有关定义字典:

>>> # empty dictionary
>>> my_dict = {}
>>>
>>> # dictionary with integer keys
>>> my_dict = { 1:'msft', 2: 'IT'}
>>>
>>> # dictionary with mixed keys
>>> my_dict = {'name': 'Aarav', 1: [ 2, 4, 10]}
>>>
>>> # using built-in function dict()
>>> my_dict = dict({1:'msft', 2:'IT'})
>>>
>>> # From sequence having each item as a pair
>>> my_dict = dict([(1,'msft'), (2,'IT')])
>>>
>>> # Accessing elements of a dictionary
>>> my_dict[1]
'msft'
>>> my_dict[2]
'IT'
>>> my_dict['IT']
Traceback (most recent call last):
   File "<pyshell#177>", line 1, in <module>
   my_dict['IT']
KeyError: 'IT'
>>>

从上面的代码中我们可以观察到:

  1. 首先,我们创建一个包含两个元素的字典,并将其分配给变量 my_dict 。每个元素都是一个键值对,整套元素用大括号括住。

  2. 数字 1 是键, msft 是它的值。类似地, 2 是键, IT 是它的值。

  3. 您可以按键获取值,但不能反过来。因此,当我们尝试 my_dict[‘IT’] 时,它会引发一个异常,因为 IT 不是一个键。

Modifying Dictionaries

观察以下代码以了解有关修改字典:

>>> # Modifying a Dictionary
>>>
>>> my_dict
{1: 'msft', 2: 'IT'}
>>> my_dict[2] = 'Software'
>>> my_dict
{1: 'msft', 2: 'Software'}
>>>
>>> my_dict[3] = 'Microsoft Technologies'
>>> my_dict
{1: 'msft', 2: 'Software', 3: 'Microsoft Technologies'}

从上面的代码中,我们能观察到 -

  1. 在一个字典中,你不能有重复的键。更改现有键的值将删除旧值。

  2. 你可以随时添加新的键值对。

  3. 字典不包含元素之间的顺序概念。它们是简单的无序集合。

Mixing Data types in a Dictionary

观察以下代码来了解在字典中混合数据类型 -

>>> # Mixing Data Types in a Dictionary
>>>
>>> my_dict
{1: 'msft', 2: 'Software', 3: 'Microsoft Technologies'}
>>> my_dict[4] = 'Operating System'
>>> my_dict
{1: 'msft', 2: 'Software', 3: 'Microsoft Technologies', 4: 'Operating System'}
>>> my_dict['Bill Gates'] = 'Owner'
>>> my_dict
{1: 'msft', 2: 'Software', 3: 'Microsoft Technologies', 4: 'Operating System',
'Bill Gates': 'Owner'}

从上面的代码中,我们能观察到 -

  1. 不仅仅是字符串,字典值可以是任何数据类型,包括字符串、整数,甚至字典本身。

  2. 与字典值不同,字典键受到更多限制,但可以是任何类型,如字符串、整数或任何其他类型。

Deleting Items from Dictionaries

观察以下代码来了解如何从字典中删除项 -

>>> # Deleting Items from a Dictionary
>>>
>>> my_dict
{1: 'msft', 2: 'Software', 3: 'Microsoft Technologies', 4: 'Operating System',
'Bill Gates': 'Owner'}
>>>
>>> del my_dict['Bill Gates']
>>> my_dict
{1: 'msft', 2: 'Software', 3: 'Microsoft Technologies', 4: 'Operating System'}
>>>
>>> my_dict.clear()
>>> my_dict
{}

从上面的代码中,我们能观察到 -

  1. del - 允许你按键从字典中删除单个项。

  2. clear - 从字典中删除所有项。

Sets

集合是一种无序集合,没有重复的元素。尽管单个项不可变,但集合本身是可变的,即我们可以向集合中添加或删除元素/项。我们可以对集合执行并集、交集等数学运算。

尽管一般集合可以使用树来实现,但 Python 中的集合可以使用哈希表来实现。这允许它使用一种高度优化的方法来检查特定元素是否包含在集合中。

Creating a set

集合是通过将所有项(元素)用逗号分隔或使用内置函数 set() 放置在花括号 {} 内创建的。观察以下代码行 -

>>> #set of integers
>>> my_set = {1,2,4,8}
>>> print(my_set)
{8, 1, 2, 4}
>>>
>>> #set of mixed datatypes
>>> my_set = {1.0, "Hello World!", (2, 4, 6)}
>>> print(my_set)
{1.0, (2, 4, 6), 'Hello World!'}
>>>

Methods for Sets

观察以下代码来了解集合的方法 -

>>> >>> #METHODS FOR SETS
>>>
>>> #add(x) Method
>>> topics = {'Python', 'Java', 'C#'}
>>> topics.add('C++')
>>> topics
{'C#', 'C++', 'Java', 'Python'}
>>>
>>> #union(s) Method, returns a union of two set.
>>> topics
{'C#', 'C++', 'Java', 'Python'}
>>> team = {'Developer', 'Content Writer', 'Editor','Tester'}
>>> group = topics.union(team)
>>> group
{'Tester', 'C#', 'Python', 'Editor', 'Developer', 'C++', 'Java', 'Content
Writer'}
>>> # intersets(s) method, returns an intersection of two sets
>>> inters = topics.intersection(team)
>>> inters
set()
>>>
>>> # difference(s) Method, returns a set containing all the elements of
invoking set but not of the second set.
>>>
>>> safe = topics.difference(team)
>>> safe
{'Python', 'C++', 'Java', 'C#'}
>>>
>>> diff = topics.difference(group)
>>> diff
set()
>>> #clear() Method, Empties the whole set.
>>> group.clear()
>>> group
set()
>>>

Operators for Sets

观察以下代码来了解集合的运算符 -

>>> # PYTHON SET OPERATIONS
>>>
>>> #Creating two sets
>>> set1 = set()
>>> set2 = set()
>>>
>>> # Adding elements to set
>>> for i in range(1,5):
   set1.add(i)
>>> for j in range(4,9):
   set2.add(j)
>>> set1
{1, 2, 3, 4}
>>> set2
{4, 5, 6, 7, 8}
>>>
>>> #Union of set1 and set2
>>> set3 = set1 | set2 # same as set1.union(set2)
>>> print('Union of set1 & set2: set3 = ', set3)
Union of set1 & set2: set3 = {1, 2, 3, 4, 5, 6, 7, 8}
>>>
>>> #Intersection of set1 & set2
>>> set4 = set1 & set2 # same as set1.intersection(set2)
>>> print('Intersection of set1 and set2: set4 = ', set4)
Intersection of set1 and set2: set4 = {4}
>>>
>>> # Checking relation between set3 and set4
>>> if set3 > set4: # set3.issuperset(set4)
   print('Set3 is superset of set4')
elif set3 < set4: #set3.issubset(set4)
   print('Set3 is subset of set4')
else: #set3 == set4
   print('Set 3 is same as set4')
Set3 is superset of set4
>>>
>>> # Difference between set3 and set4
>>> set5 = set3 - set4
>>> print('Elements in set3 and not in set4: set5 = ', set5)
Elements in set3 and not in set4: set5 = {1, 2, 3, 5, 6, 7, 8}
>>>
>>> # Check if set4 and set5 are disjoint sets
>>> if set4.isdisjoint(set5):
   print('Set4 and set5 have nothing in common\n')
Set4 and set5 have nothing in common
>>> # Removing all the values of set5
>>> set5.clear()
>>> set5 set()