面向对象的快捷方式

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

Python内置函数

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()函数

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

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

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

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

然而,实际上,我们更喜欢 len()而不是 __ len __()函数由于以下原因而减去;

  • 效率更高.并且没有必要编写特定方法来拒绝访问特殊方法,例如__len __.

  • 这很容易维护.

  • 它支持向后兼容性.

反转(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 __ 时,结果会有非常不同.

输出

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

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

枚举

enumerate()方法将计数器添加到迭代并返回枚举对象.

enumerate()的语法是 :

enumerate( iterable,start = 0)

这里第二个参数 start 是可选的,默认索引以为零开始(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,setattr delattr,它们允许对象的属性被操作字符串名称.

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

  • nzip,需要两个或更多序列并返回一个新的元组序列,其中每个元组包含每个序列的单个值.

文件I/O

文件的概念与术语object-orie相关联编程. 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')

输出

 
 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 __()方法的对象都可以使用函数调用语法调用.