Object Oriented Python 简明教程

Object Oriented Python - Data Structures

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

Python data structures are very intuitive from a syntax point of view and they offer a large choice of operations. You need to choose Python data structure depending on what the data involves, if it needs to be modified, or if it is a fixed data and what access type is required, such as at the beginning/end/random etc.

Lists

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

A List represents the most versatile type of data structure in Python. A list is a container which holds comma-separated values (items or elements) between square brackets. Lists are helpful when we want to work with multiple related values. As lists keep data together, we can perform the same methods and operations on multiple values at once. Lists indices start from zero and unlike strings, lists are mutable.

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

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

Each item of a list is assigned a number – that is the index or position of that number.Indexing always start from zero, the second index is one and so forth. To access items in a list, we can use these index numbers within a square bracket. Observe the following code for example −

>>> 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 are the simplest and most basic Python built-in types. We have used them multiple times without noticing and have extended it to every class we have created. The main purpose to write an empty class is to block something for time being and later extend and add a behavior to it.

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

To add a behavior to a class means to replace a data structure with an object and change all references to it. So it is important to check the data, whether it is an object in disguise, before you create anything. Observe the following code for better understanding:

>>> #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 允许一个对象拥有任意属性时,它会占用一定数量的系统内存来跟踪每个对象具有的属性,以便同时存储属性名称和属性值。即使没有存储任何属性,也会为潜在的新属性分配一定数量的内存。

So from above, we can see it’s not possible to set any attributes on an object that was instantiated directly. When Python allows an object to have arbitrary attributes, it takes a certain amount of system memory to keep track of what attributes each object has, for storing both the attribute name and its value. Even if no attributes are stored, a certain amount of memory is allocated for potential new attributes.

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

So Python disables arbitrary properties on object and several other built-ins, by default.

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

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

Hence, if we want to group properties together, we could store them in an empty object as shown in the code above. However, this method is not always suggested. Remember that classes and objects should only be used when you want to specify both data and behaviors.

Tuples

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

Tuples are similar to lists and can store elements. However, they are immutable, so we cannot add, remove or replace objects. The primary benefits tuple provides because of its immutability is that we can use them as keys in dictionaries, or in other locations where an object requires a hash value.

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

Tuples are used to store data, and not behavior. In case you require behavior to manipulate a tuple, you need to pass the tuple into a function(or method on another object) that performs the action.

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

As tuple can act as a dictionary key, the stored values are different from each other. We can create a tuple by separating the values with a comma. Tuples are wrapped in parentheses but not mandatory. The following code shows two identical assignments .

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

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

Tuples are very similar to list except that the whole set of elements are enclosed in parentheses instead of square brackets.

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

Just like when you slice a list, you get a new list and when you slice a tuple, you get a new 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 元组中的方法:

The following code shows the methods in Python tuples −

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

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

From the code shown above, we can understand that tuples are immutable and hence −

  1. You cannot add elements to a tuple.

  2. You cannot append or extend a method.

  3. You cannot remove elements from a tuple.

  4. Tuples have no remove or pop method.

  5. Count and index are the methods available in a tuple.

Dictionary

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

Dictionary is one of the Python’s built-in data types and it defines one-to-one relationships between keys and values.

Defining Dictionaries

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

Observe the following code to understand about defining a dictionary −

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

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

From the above code we can observe that:

  1. First we create a dictionary with two elements and assign it to the variable my_dict. Each element is a key-value pair, and the whole set of elements is enclosed in curly braces.

  2. The number 1 is the key and msft is its value. Similarly, 2 is the key and IT is its value.

  3. You can get values by key, but not vice-versa. Thus when we try my_dict[‘IT’] , it raises an exception, because IT is not a key.

Modifying Dictionaries

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

Observe the following code to understand about modifying a dictionary −

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

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

From the above code we can observe that −

  1. You cannot have duplicate keys in a dictionary. Altering the value of an existing key will delete the old value.

  2. You can add new key-value pairs at any time.

  3. Dictionaries have no concept of order among elements. They are simple unordered collections.

Mixing Data types in a Dictionary

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

Observe the following code to understand about 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'}

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

From the above code we can observe that −

  1. Not just strings but dictionary value can be of any data type including strings, integers, including the dictionary itself.

  2. Unlike dictionary values, dictionary keys are more restricted, but can be of any type like strings, integers or any other.

Deleting Items from Dictionaries

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

Observe the following code to understand about deleting items from a dictionary −

>>> # 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
{}

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

From the above code we can observe that −

  1. del − lets you delete individual items from a dictionary by key.

  2. clear − deletes all items from a dictionary.

Sets

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

Set() is an unordered collection with no duplicate elements. Though individual items are immutable, set itself is mutable, that is we can add or remove elements/items from the set. We can perform mathematical operations like union, intersection etc. with set.

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

Though sets in general can be implemented using trees, set in Python can be implemented using a hash table. This allows it a highly optimized method for checking whether a specific element is contained in the set

Creating a set

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

A set is created by placing all the items (elements) inside curly braces {}, separated by comma or by using the built-in function set(). Observe the following lines of code −

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

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

Observe the following code to understand about 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

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

Observe the following code to understand about 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()