面向对象捷径

本章详细讨论Python中的各种内置函数,文件I/O操作和重载概念。

Python内置函数

Python解释器有许多称为内置函数的函数,可以随时使用。 在其最新版本中,Python包含68个内置函数,如下表所列 -

any() divmod() id() object() sorted()
ascii() enumerate() input() oct() staticmethod()
bin() eval() int() open() str()
bool() exec() isinstance() ord() sum()
bytearray() filter() issubclass() pow() super()
bytes() float() iter() print() tuple()
callable() format() len() property() type()
chr() frozenset() list() range() vars()
classmethod() getattr() locals() repr() zip()
compile() globals() map() reversed() import()
complex() hasattr() max() round( -
delattr() hash() memoryview() set() -

本节简要介绍一些重要函数/功能 -

len()函数

len()函数获取字符串,列表或集合的长度。 它返回对象的项目的长度或数量,其中对象可以是字符串,列表或集合。

>>> len(['hello', 9 , 45.0, 24])
4

len()函数内部工作方式如list.__len__()tuple.__ len __()。 因此,请注意,len()仅适用于具有__len __()方法的对象。

>>> set1
{1, 2, 3, 4}
>>> set1.__len__()
4

但是,在实践中,我们更顷向于使用len()而不是__len __()函数,原因如下 -

  • 它更高效。 并且写一个特定的方法来拒绝访问诸如__len__这样的特殊方法是没有必要的。
  • 它易于维护。
  • 它支持向后兼容性。

Reversed(seq)方法

它返回反向迭代器。 seq必须是具有__reversed __()方法或支持序列协议(__len __()方法和__getitem __()方法)的对象。 当我们想从后到前循环项目时,它通常用于循环。

>>> normal_list = [2, 4, 5, 7, 9]
>>>
>>> class CustomSequence():
   def __len__(self):
      return 5
   def __getitem__(self,index):
      return "x{0}".format(index)
>>> class funkyback():
   def __reversed__(self):
      return 'backwards!'
>>> for seq in normal_list, CustomSequence(), funkyback():
      print('\n{}: '.format(seq.__class__.__name__), end="")
      for item in reversed(seq):
         print(item, end=", ")

最后的for循环打印正常列表的反转列表,以及两个自定义序列的实例。 输出显示revers()适用于它们中的所有三个,但是当定义__reversed__时,结果会有很大不同。

执行上面给出的代码时,可以观察到以下输出 -

list: 9, 7, 5, 4, 2,
CustomSequence: x4, x3, x2, x1, x0,
funkyback: b, a, c, k, w, a, r, d, s, !,

枚举
enumerate()方法向iterable添加一个计数器并返回枚举对象。
enumerate()的语法是 -

enumerate(iterable, start = 0)

这里第二个参数起始是可选的,默认情况下索引从零开始(0)。

>>> # Enumerate
>>> names = ['Rajesh', 'Rahul', 'Aarav', 'Sahil', 'Trevor']
>>> enumerate(names)
<enumerate object at 0x031D9F80>
>>> list(enumerate(names))
[(0, 'Rajesh'), (1, 'Rahul'), (2, 'Aarav'), (3, 'Sahil'), (4, 'Trevor')]
>>>

因此·enumerate()·返回一个迭代器,它产生一个元组,用于保持传递的序列中元素的计数。 由于返回值是一个迭代器,直接访问它并没有多大用处。 enumerate()的更好方法是将计数保持在for循环中。

>>> for i, n in enumerate(names):
   print('Names number: ' + str(i))
   print(n)
Names number: 0
Rajesh
Names number: 1
Rahul
Names number: 2
Aarav
Names number: 3
Sahil
Names number: 4
Trevor

标准库中还有许多其他功能,下面是另一些更广泛使用的功能列表 -

  • hasattrgetattrsetattrdelattr,它允许对象的属性由其字符串名称操作。
  • allany,接受可迭代对象,如果所有或任何项目评估为真,则返回True
  • nzip,它采用两个或多个序列并返回一个新的元组序列,其中每个元组包含每个序列的单个值。

文件I/O

文件的概念与术语面向对象编程相关。 Python封装了操作系统在抽象中提供的接口,使我们可以使用文件对象。

open()内置函数用于打开文件并返回文件对象。 它是两个参数中最常用的函数 -

open(filename, mode)

open()函数调用两个参数,第一个是文件名,第二个是模式。 这里的模式可以是只读模式的'r',只有写入的模式'w'(同名的现有文件将被删除),'a'打开要附加的文件,任何写入文件的数据都会自动添加 到最后。 'r +'打开文件进行读写。 默认模式是只读的。

在窗口中,模式附加的'b'以二进制模式打开文件,所以也有'rb''wb''r + b'等模式。

>>> text = 'This is the first line'
>>> file = open('datawork','w')
>>> file.write(text)
22
>>> file.close()

在某些情况下,我们只想附加到现有文件而不是覆盖它,因为可以提供值'a'作为模式参数,附加到文件的末尾,而不是完全覆盖现有文件内容。

>>> f = open('datawork','a')
>>> text1 = ' This is second line'
>>> f.write(text1)
20
>>> f.close()

当打开一个文件进行读取,可以调用readreadlinereadlines方法来获取文件的内容。 read方法将文件的全部内容作为strbytes对象返回,具体取决于第二个参数是否为'b'

为了便于阅读,并且为了避免一次性读取大文件,通常最好直接在文件对象上使用for循环。 对于文本文件,它将逐行读取每一行,并且可以在循环体内处理它。 但对于二进制文件,最好使用read()方法读取固定大小的数据块,并传递参数以获取最大字节数。

>>> f = open('fileone','r+')
>>> f.readline()
'This is the first line. \n'
>>> f.readline()
'This is the second line. \n'

通过对文件对象的写入方法写入文件将向该文件写入一个字符串(二进制数据的字节)对象。 writelines方法接受一系列字符串并将每个迭代值写入文件。 writelines方法不在序列中的每个项目之后追加一个新行。

最后,在完成读取或写入文件时,应调用close()方法,以确保将任何缓冲写入写入磁盘,文件已被正确清理,并将与该文件绑定的所有资源释放回操作系统。 调用close()方法是一个更好的方法,但从技术上讲,这将在脚本存在时自动发生。

方法重载的替代方法
方法重载是指具有多个接受不同参数集的同名方法。

给定单个方法或函数,可以指定自己的参数数量。 根据函数定义,可以使用零个,一个,两个或多个参数来调用它。

class Human:
   def sayHello(self, name = None):
      if name is not None:
         print('Hello ' + name)
      else:
         print('Hello ')

#Create Instance
obj = Human()

#Call the method, else part will be executed
obj.sayHello()

#Call the method with a parameter, if part will be executed
obj.sayHello('Rahul')

执行上面示例代码,得到以下结果 -

Hello
Hello Rahul

默认参数

函数也是对象
可调用对象是一个对象可以接受一些参数,并可能返回一个对象。 函数是Python中最简单的可调用对象,但也有其他类似于类或某些类实例。

Python中的每个函数都是一个对象。 对象可以包含方法或函数,但对象不是必需的函数。

def my_func():
   print('My function was called')
my_func.description = 'A silly function'
def second_func():

   print('Second function was called')

   second_func.description = 'One more sillier function'

def another_func(func):
   print("The description:", end=" ")
   print(func.description)
   print('The name: ', end=' ')
   print(func.__name__)
   print('The class:', end=' ')
   print(func.__class__)
   print("Now I'll call the function passed in")
   func()

another_func(my_func)
another_func(second_func)

在上面的代码中,可以将两个不同的函数作为参数传递给第三个函数,并为每个函数获取不同的输出 -

The description: A silly function
The name: my_func
The class: 
Now I'll call the function passed in
My function was called
The description: One more sillier function
The name: second_func
The class: 
Now I'll call the function passed in
Second function was called

可调用的对象

就像函数是可以在其上设置属性的对象一样,可以创建一个可以被调用的对象,就像它是一个函数一样。

在Python中,可以使用函数调用语法来调用带有__call __()方法的任何对象。


上一篇: 构建块 下一篇: 继承和多态