search
HomeBackend DevelopmentPython TutorialPython专用方法与迭代机制实例分析

本文实例讲述了Python专用方法与迭代机制,分享给大家供大家参考之用。具体分析如下:

众所周知,Python 设计哲学是“优雅”、“明确”、“简单”,对于一件事只用一种最好的方法来做,而这种优雅在于背后很自然的隐藏了很多细节。比如对一些对象直接用for 语句来迭代,一些全局函数可以作用于很多具有共同特征的对象,还有生成器装饰器自省等特性。其中很多实现都是借助 Python  内部专用方法,而对外则使用统一的全局函数来进行操作,在配合一些语法糖,使得 Python 写起来愈发的方便,符合人的直觉。

Python 专用方法

类的私有方法:以双线划线开头,但是不以双下划线结尾的方法;
类的专有方法:以双下划线开头和结尾,常用来被内建函数调用;
模块私有对象:以单下划线开头,不能被导入到其他的模块中去;

#!/usr/bin/env python 
# Python3 实现 
_modeluprivate = '本模块私有'  #不能用 from module import * 导入 
 
class People(): 
  def __myprivate(self): 
    print("This is a private fun") 
  def __test__(self): 
    print('call __private: ',end='') 
    self.__myprivate() 
 
if __name__ == '__main__': 
  a = People() 
  a.__test__()      # 专有方法,一般系统专用,自己的类方法不要用这种新式命名 
  a._People__myprivate() # 私有方法被对外被翻译成了这种名字,从而达到私有的效果 
  print(_modeluprivate) 
   
''''' 
输出 
call __private: This is a private fun 
This is a private fun 
本模块私有 
''' 

Python 迭代机制

Python 中的可迭代对象是实现了 __iter__() 方法的对象,而 __iter__() 方法返回一个迭代器对象,迭代器对象内部要实现 __next__() 方法。迭代器对外提供了一个统一的遍历集合的接口,并且可以直接用 for 语句来进行操作,非常的方便。对于一些特别大甚至无限的集合,迭代器避免了一次性将数据集载入,几乎是唯一的访问方法。

#!/usr/bin/env python 
# Python3 实现 
class IterTest(): 
  def __init__(self): 
    self.a = 0 
  def __iter__(self): 
    return self 
  def __next__(self): 
    self.a += 1 
    if self.a > 3: 
      raise StopIteration 
    return self.a 
 
if __name__ == '__main__': 
  a = IterTest() 
  for i in a: 
    print(i,end=' ') 
  b = IterTest() 
  print(list(b)) # list()构造器,可以接受可迭代对象 
  c = IterTest() 
  print(next(c), next(c), next(c)) 
 
''''' 
输出 
1 2 3 [1, 2, 3] 
1 2 3 
''' 

Python 的生成器其实返回的也是一个迭代器,同样可以对其使用 next() 函数,对其使用 for操作,有了 yield 关键字使得创建生成器更加的方便。

#!/usr/bin/env python 
# Python3 实现 
def funGenerate(): 
  yield 1 
  yield 2 
  yield 3 
 
if __name__ == '__main__': 
  a = funGenerate() 
  for i in a: 
    print(i, end=' ') 
  b = funGenerate() 
  print(next(b),next(b),next(b)) 
 
''''' 
输出 
1 2 3 1 2 3 
'''

希望本文所述对大家Python程序设计的学习有所帮助。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python: A Deep Dive into Compilation and InterpretationPython: A Deep Dive into Compilation and InterpretationMay 12, 2025 am 12:14 AM

Pythonusesahybridmodelofcompilationandinterpretation:1)ThePythoninterpretercompilessourcecodeintoplatform-independentbytecode.2)ThePythonVirtualMachine(PVM)thenexecutesthisbytecode,balancingeaseofusewithperformance.

Is Python an interpreted or a compiled language, and why does it matter?Is Python an interpreted or a compiled language, and why does it matter?May 12, 2025 am 12:09 AM

Pythonisbothinterpretedandcompiled.1)It'scompiledtobytecodeforportabilityacrossplatforms.2)Thebytecodeistheninterpreted,allowingfordynamictypingandrapiddevelopment,thoughitmaybeslowerthanfullycompiledlanguages.

For Loop vs While Loop in Python: Key Differences ExplainedFor Loop vs While Loop in Python: Key Differences ExplainedMay 12, 2025 am 12:08 AM

Forloopsareidealwhenyouknowthenumberofiterationsinadvance,whilewhileloopsarebetterforsituationswhereyouneedtoloopuntilaconditionismet.Forloopsaremoreefficientandreadable,suitableforiteratingoversequences,whereaswhileloopsoffermorecontrolandareusefulf

For and While loops: a practical guideFor and While loops: a practical guideMay 12, 2025 am 12:07 AM

Forloopsareusedwhenthenumberofiterationsisknowninadvance,whilewhileloopsareusedwhentheiterationsdependonacondition.1)Forloopsareidealforiteratingoversequenceslikelistsorarrays.2)Whileloopsaresuitableforscenarioswheretheloopcontinuesuntilaspecificcond

Python: Is it Truly Interpreted? Debunking the MythsPython: Is it Truly Interpreted? Debunking the MythsMay 12, 2025 am 12:05 AM

Pythonisnotpurelyinterpreted;itusesahybridapproachofbytecodecompilationandruntimeinterpretation.1)Pythoncompilessourcecodeintobytecode,whichisthenexecutedbythePythonVirtualMachine(PVM).2)Thisprocessallowsforrapiddevelopmentbutcanimpactperformance,req

Python concatenate lists with same elementPython concatenate lists with same elementMay 11, 2025 am 12:08 AM

ToconcatenatelistsinPythonwiththesameelements,use:1)the operatortokeepduplicates,2)asettoremoveduplicates,or3)listcomprehensionforcontroloverduplicates,eachmethodhasdifferentperformanceandorderimplications.

Interpreted vs Compiled Languages: Python's PlaceInterpreted vs Compiled Languages: Python's PlaceMay 11, 2025 am 12:07 AM

Pythonisaninterpretedlanguage,offeringeaseofuseandflexibilitybutfacingperformancelimitationsincriticalapplications.1)InterpretedlanguageslikePythonexecuteline-by-line,allowingimmediatefeedbackandrapidprototyping.2)CompiledlanguageslikeC/C transformt

For and While loops: when do you use each in python?For and While loops: when do you use each in python?May 11, 2025 am 12:05 AM

Useforloopswhenthenumberofiterationsisknowninadvance,andwhileloopswheniterationsdependonacondition.1)Forloopsareidealforsequenceslikelistsorranges.2)Whileloopssuitscenarioswheretheloopcontinuesuntilaspecificconditionismet,usefulforuserinputsoralgorit

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft