python猴子补丁_python-通过猴子补丁覆盖方法

我试图弄清楚以下示例为什么行不通.

class BaseClass(object):

def __init__(self):

self.count = 1

def __iter__(self):

return self

def next(self):

if self.count:

self.count -= 1

return self

else:

raise StopIteration

class DerivedNO(BaseClass):

pass

class DerivedO(BaseClass):

def __init__(self):

self.new_count = 2

self.next = self.new_next

def new_next(self):

if self.new_count:

self.new_count -= 1

return None

else:

raise StopIteration

x = DerivedNO()

y = DerivedO()

print x

print list(x)

print y

print list(y)

这是输出:

[<__main__.derivedno object at>]

Traceback (most recent call last):

File "playground.py", line 41, in

print list(y)

File "playground.py", line 11, in next

if self.count:

AttributeError: 'DerivedO' object has no attribute 'count'

如您所见,当我尝试在__init__中分配next()方法时,新方法将不会在DerivedO中被覆盖.这是为什么?一个简单的next调用可以很好地工作,但是在使用迭代技术时根本无法工作.

编辑:我意识到我的问题还不完全清楚. AttributeError不是我要解决的问题.但这确实表明next()是在BaseClass上调用的,而不是像我认为的那样在DerivedO上调用的.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值