关于这个主题的核心Python编程一书中的一个例子Delegation似乎没有工作......或者可能是我没有清楚地理解这个主题..
下面是代码,其中类CapOpen包装file对象并定义file在write模式下打开时的修改行为.它应该只在UPPERCASE中写入所有字符串.
但是,当我尝试打开文件进行读取,并迭代它以打印每一行时,我得到以下异常:
Traceback (most recent call last):
File "D:/_Python Practice/Core Python Programming/chapter_13_Classes/
WrappingFileObject.py", line 29, in <module>
for each_line in f:
TypeError: 'CapOpen' object is not iterable
Run Code Online (Sandbox Code Playgroud)
这很奇怪,因为虽然我没有明确定义迭代器方法,但我希望将调用委托__getattr__给底层file对象.这是代码.我错过了什么吗?
class CapOpen(object):
def __init__(self, filename, mode='r', buf=-1):
self.file = open(filename, mode, buf)
def __str__(self):
return str(self.file)
def __repr__(self):
return `self.file`
def write(self, line):
self.file.write(line.upper())
def __getattr__(self, attr):
return getattr(self.file, attr)
f = CapOpen('wrappingfile.txt', 'w')
f.write('delegation …Run Code Online (Sandbox Code Playgroud) 可能重复:
构建一个基本的Python迭代器
定义迭代器所需的方法是什么?例如,在下面的Infinity迭代器中,它的方法是否足够?是否有其他标准或de因子标准方法定义迭代器?
class Infinity(object):
def __init__(self):
self.current = 0
def __iter__(self):
return self
def next(self):
self.current += 1
return self.current
Run Code Online (Sandbox Code Playgroud) 一些地方在网上,其中包括堆栈溢出的答案(如这个,这个和这个),提到了Python迭代器必须实现的__next__方法(我的理解)和该__iter__方法。这些地方正确地得出结论,所有迭代器也是可迭代的。如果注释为 a 的变量typing.Iterator未实现该__iter__方法,则即使 PyCharm 也会发出类型警告。
与这些相反,关于迭代器的官方 Python 教程部分只提到需要一个__next__方法:
该函数返回一个迭代器对象,该对象定义了
__next__()一次访问容器中元素的方法
所以我的问题是:Python 迭代器是否正式需要自己成为可迭代对象?我个人不明白为什么这应该是真的,以及为什么我们不能完全分离 anIterable和 an的要求Iterator。
我试图将自定义类从Python 2移植到Python3。我找不到正确的语法来移植该类的迭代器。这是真实类的MVCE,到目前为止我仍在尝试解决此问题:
工作的Python 2代码:
class Temp:
def __init__(self):
self.d = dict()
def __iter__(self):
return self.d.iteritems()
temp = Temp()
for thing in temp:
print(thing)
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,iteritems()在Python 3中中断。根据这个广受好评的答案,“ dict.items现在dict.iteritems在python 2中做了事情”。所以我接下来尝试了:
class Temp:
def __init__(self):
self.d = dict()
def __iter__(self):
return self.d.items()
Run Code Online (Sandbox Code Playgroud)
上面的代码产生“ TypeError: iter() returned non-iterator of type 'dict_items'”
根据此答案,Python 3除了iter方法之外,还需要可迭代的对象提供next()方法。好吧,字典也是可迭代的,因此在我的用例中,我应该能够只传递字典的next和iter方法,对吗?
class Temp:
def __init__(self):
self.d = dict()
def __iter__(self):
return self.d.__iter__
def next(self):
return self.d.next
Run Code Online (Sandbox Code Playgroud)
这次给了我“ TypeError: iter() returned non-iterator of type 'method-wrapper'”。 …
据我所知,我可以使用返回迭代器for的__iter__方法在对象上使用循环构造.我有一个对象,我实现了以下__getattribute__方法:
def __getattribute__(self,name):
if name in ["read","readlines","readline","seek","__iter__","closed","fileno","flush","mode","tell","truncate","write","writelines","xreadlines"]:
return getattr(self.file,name)
return object.__getattribute__(self,name)
Run Code Online (Sandbox Code Playgroud)
我有这个类的对象,a发生以下情况:
>>> hasattr(a,"__iter__")
True
>>> for l in a: print l
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'TmpFile' object is not iterable
>>> for l in a.file: print l
...
>>>
Run Code Online (Sandbox Code Playgroud)
所以python看到a有一个__iter__方法,但不认为它是可迭代的.我做错了什么?这是python 2.6.4.
嗨,所以我试图弄清楚如何使用Python创建一个迭代器对象,删除重复项或更多,以便省略重复.
例如,我有一个列表(1,2,3,3,4,4,5),我得到(1,2,3,4,5)
我明白为了获得迭代器对象,我必须创建它.所以:
Class Unique:
def __init__(self, n):
self.i = 0
self.n = n
def __iter__(self):
return self
def __next__(self):
if self.i < self.n:
Run Code Online (Sandbox Code Playgroud)
我实际上并不完全确定在这个问题上接下来要做什么.在此先感谢任何意见或帮助!
我正在尝试为Web资源(延迟获取的图像)实现可迭代的代理。
首先,我做到了(返回id,在生产中,这些将是图像缓冲区)
def iter(ids=[1,2,3]):
for id in ids:
yield id
Run Code Online (Sandbox Code Playgroud)
效果很好,但现在我需要保持状态。
我阅读了定义迭代器的四种方法。我判断迭代器协议是要走的路。跟随我的尝试和失败,以实现这一目标。
class Test:
def __init__(me, ids):
me.ids = ids
def __iter__(me):
return me
def __next__(me):
for id in me.ids:
yield id
raise StopIteration
test = Test([1,2,3])
for t in test:
print('new value', t)
Run Code Online (Sandbox Code Playgroud)
输出:
new value <generator object Test.__next__ at 0x7f9c46ed1750>
new value <generator object Test.__next__ at 0x7f9c46ed1660>
new value <generator object Test.__next__ at 0x7f9c46ed1750>
new value <generator object Test.__next__ at 0x7f9c46ed1660>
new value <generator object Test.__next__ …Run Code Online (Sandbox Code Playgroud) 这是我的代码,我用它来打开excel表,然后将每行作为字符串列表返回(其中每个单元格都是一个字符串).该类返回一个列表,该列表填充了与文件中的行一样多的列表.所以50行将返回50个列表.
from xlrd import open_workbook
class ExcelReadLines(object):
def __init__(self,path_to_file):
'''Accepts the Excel File'''
self.path_to_file = path_to_file
self.__work__()
def __work__(self):
self.full_file_as_read_lines = []
self.book = open_workbook(self.path_to_file)
self.sheet = self.book.sheet_by_index(0)
for row_index in range(self.sheet.nrows):
single_read_lines = []
for col_index in range(self.sheet.ncols):
cell_value_as_string = str(self.sheet.cell(row_index,col_index).value)
cell_value_stripped = cell_value_as_string.strip('u')
single_read_lines.append(cell_value_stripped)
self.full_file_as_read_lines.append(single_read_lines)
return self.full_file_as_read_lines
Run Code Online (Sandbox Code Playgroud)
但是当我跑步时:
for x in ExcelReader('excel_sheet'): print x
Run Code Online (Sandbox Code Playgroud)
我收到错误消息:
class is not iterable
Run Code Online (Sandbox Code Playgroud) 这肯定是重复的,但是说我有一个类如下:
class MyObj(object):
def __init__(self, *args, **kwargs):
self._data = [2, 1, 3]
self._more_data = [False, True, False]
Run Code Online (Sandbox Code Playgroud)
我怎样才能使它可以排序,而不是与其他MyObj对象(我可以用它做__lt__),但在内部?所以如果我打电话给sorted(my_obj_instance)我得到一个包含以下数据的版本:
self._data = [1,2,3]
self._more_data [True, False, False]
Run Code Online (Sandbox Code Playgroud)
也就是说,_data按数字排序,_more_data已相应排序.
我正在使用以下代码来抓取该网站(http://profiles.ehs.state.ma.us/Profiles/Pages/ChooseAPhysician.aspx?Page=1);但是,获取以下TypeError:
“文件“ C:\ Users \ Anaconda2 \ lib \ site-packages \ scrapy \ contrib \ spiders \ crawl.py”,第83行,位于_compile_rules self._rules = [self.rules中的r的copy.copy(r)] TypeError:“ Rule”对象不可迭代”
我在第83行上没有编写任何代码,因此想知道是否有人对如何解决此问题有想法?我在Windows中使用Python 2.7。
谢谢!
from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import scrapy
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors import LinkExtractor
from scrapy.selector import HtmlXPathSelector
class MdiMassSpider(CrawlSpider):
name = "MdiMass"
allowed_domains = ["http://profiles.ehs.state.ma.us/Profiles/Pages/FindAPhysician.aspx"]
start_urls = ["http://profiles.ehs.state.ma.us/Profiles/Pages/ChooseAPhysician.aspx?Page=1"]
driver = webdriver.Chrome()
rules …Run Code Online (Sandbox Code Playgroud) 我试图弄清楚如何让这个类在 Python 3 中工作,它在 Python 2 中工作。这是来自 D. Beasley 的生成器教程。我是 Python 新手,只是在网上学习教程。
蟒蛇 2
class countdown(object):
def __init__(self, start):
self.count = start
def __iter__(self):
return self
def next(self):
if self.count <= 0:
raise StopIteration
r = self.count
self.count -= 1
return r
c = countdown(5)
for i in c:
print i,
Run Code Online (Sandbox Code Playgroud)
Python 3,不工作。
class countdown(object):
def __init__(self, start):
self.count = start
def __iter__(self):
return self
def next(self):
if self.count <= 0:
raise StopIteration
r = self.count
self.count -= 1
return …Run Code Online (Sandbox Code Playgroud) 我有以下代码是我为一门运行良好的课程编写的:
def reverse_iter(iterable):
"""Return a generator that yields items from iterable in reverse order"""
last = len(iterable) - 1
while last >= 0:
yield iterable[last]
last -= 1
Run Code Online (Sandbox Code Playgroud)
作业的下一部分是把这个函数变成一个类。我知道这不切实际,但这是被问到的。我对类的了解非常有限,但我想出了以下代码:
class ReverseIter:
"""Class whose instances iterate the initial iterable in reverse order"""
def __init__(self, iterable):
self.iterable = iterable
def iterreverse(self):
last = len(self.iterable) - 1
while last >= 0:
yield self.iterable[last]
last -= 1
nums = [1, 2, 3, 4]
it = ReverseIter(nums)
print(iter(it) is it)
print(next(it) == 4)
print(next(it))
print(next(it)) …Run Code Online (Sandbox Code Playgroud) python ×12
iterator ×7
python-2.7 ×4
python-3.x ×4
iterable ×2
class ×1
dictionary ×1
for-loop ×1
interface ×1
object ×1
selenium ×1
sorting ×1
web-crawler ×1