【发布时间】:2018-11-16 02:37:03
【问题描述】:
我试图理解为什么一个函数可以作为外部函数工作,但如果我将它作为方法移到类中就无法工作。
很快我就创建了一个链表类:
class Link:
"""A linked list."""
empty = ()
def __init__(self, first, rest=empty):
assert rest is Link.empty or isinstance(rest, Link)
self.first = first
self.rest = rest
def __str__(self):
string = '<'
while self.rest is not Link.empty:
string += str(self.first) + ', '
self = self.rest
return string + str(self.first) + '>'
所以当我尝试创建一个名为stretch的函数时,我可以:
def stretch(s, repeat=0):
"""Replicate the kth element k times, for all k in s."""
if s is not Link.empty:
stretch(s.rest, repeat+1)
for i in range(repeat):
s.rest = Link(s.first, s.rest)
成功了:
a = Link(3, Link(4, Link(5, Link(6))))
print(a) # >>> <3, 4, 5, 6>
stretch(a)
print(a) # >>> <3, 4, 4, 5, 5, 5, 6, 6, 6, 6>
但是,当我尝试将此函数创建为类方法时:
def stretch(self, repeat=0):
"""Replicate the kth element k times, for all k in a linked list."""
if self is not Link.empty:
self.rest.stretch(repeat+1)
for i in range(repeat):
self.rest = Link(self.first, self.rest)
现在不行了:
b = Link(3, Link(4, Link(5, Link(6))))
b.stretch()
print(b)
# >>> AttributeError: 'tuple' object has no attribute 'stretch'
我知道当b 到达最后一个元素时,b.rest 将是一个空元组,但在方法中,它说if self is not Link.empty 它不应该执行任何操作。为什么它给我错误信息?
谢谢!
【问题讨论】:
-
你定义了第二个
stretch在类吗? -
@DYZ 我当然做到了。
-
问问自己:
self是Link的实例,曾经Link.empty是不是实例Link?
标签: python oop linked-list