目录

面向对象的快捷方式(Object Oriented Shortcuts)

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

Python Built-in Functions

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

内置功能
abs()dict()help()min()setattr()
all()dir()hex()next()slice()
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() function

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

>>> 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 __()方法)的对象。 当我们想要从后到前循环项目时,它通常用于for循环。

>>> 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循环打印正常列表的反转列表,以及两个自定义序列的实例。 输出显示__reversed__ reversed()适用于它们中的所有三个,但是当我们定义__reversed__时,结果会有很大不同。

输出 (Output)

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

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

枚举(Enumerate)

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

enumerate()的语法是 -

enumerate(iterable, start = 0)

这里第二个参数start是可选的,默认情况下,index以零(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

标准库中还有许多其他函数,这是另一个更广泛使用的函数列表 -

  • hasattr, getattr, setattrdelattr,它允许通过字符串名称操纵对象的属性。

  • allany,接受可迭代对象,如果所有或任何项目评估为True则返回True

  • nzip,它接受两个或多个序列并返回一个新的元组序列,其中每个元组包含每个序列的单个值。

File 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()

打开文件进行读取后,我们可以调用read,readline或readlines方法来获取文件的内容。 read方法将文件的全部内容作为str或bytes对象返回,具体取决于第二个参数是否为“b”。

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

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

写入文件,通过文件对象上的write方法将字符串(二进制数据的字节)对象写入文件。 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')

输出 (Output)

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: <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: <class>
Now I'll call the function passed in
Second function was called
</class></class>

可调用的对象

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

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

↑回到顶部↑
WIKI教程 @2018