用python调用我的类时出现问题
我不知道如何保持这个简单。。。我也希望有人看看我的代码,告诉我为什么我的函数不能正常工作 我有一门课:用python调用我的类时出现问题,python,class,inheritance,Python,Class,Inheritance,我不知道如何保持这个简单。。。我也希望有人看看我的代码,告诉我为什么我的函数不能正常工作 我有一门课: class PriorityQueue(object): '''A class that contains several methods dealing with queues.''' def __init__(self): '''The default constructor for the PriorityQueue class, an empty list.
class PriorityQueue(object):
'''A class that contains several methods dealing with queues.'''
def __init__(self):
'''The default constructor for the PriorityQueue class, an empty list.'''
self.q = []
def insert(self, number):
'''Inserts a number into the queue, and then sorts the queue to ensure that the number is in the proper position in the queue.'''
self.q.append(number)
self.q.sort()
def minimum(self):
'''Returns the minimum number currently in the queue.'''
return min(self.q)
def removeMin(self):
'''Removes and returns the minimum number from the queue.'''
return self.q.pop(0)
def __len__(self):
'''Returns the size of the queue.'''
return self.q.__len__()
def __str__(self):
'''Returns a string representing the queue.'''
return "{}".format(self.q)
def __getitem__(self, key):
'''Takes an index as a parameter and returns the value at the given index.'''
return self.q[key]
def __iter__(self):
return self.q.__iter__()
我有一个函数,它将获取一个文本文件,并通过类中的一些方法运行它:
def testQueue(fname):
infile = open(fname, 'r')
info = infile.read()
infile.close()
info = info.lower()
lstinfo = info.split()
queue = PriorityQueue()
for item in range(len(lstinfo)):
if lstinfo[item] == "i":
queue.insert(eval(lstinfo[item + 1]))
if lstinfo[item] == "s":
print(queue)
if lstinfo[item] == "m":
queue.minimum()
if lstinfo[item] == "r":
queue.removeMin()
if lstinfo[item] == "l":
len(queue)
#if lstinfo[item] == "g":
对我不起作用的是对queue.minimum
和queue.removeMin()的调用
我完全感到困惑,因为如果我在shell中手动执行此操作,一切都会工作,当我读取文件并从文件中的字母中获取指令时,它也会工作,但是minimum
和removeMin()
不会在shell中显示值,removeMin()
但是将从列表中删除最低的数字
我做错了什么,它没有显示它正在做什么,就像类方法定义的那样
即:
当我从函数调用它时,它不应该显示最小值吗?否,定义最小值(self):return min(self.q)
在调用时不会显示任何内容。只有在打印输出时,它才会显示一些内容,如print(queue.minimum())
中所示。例外情况是从Python提示符/REPL执行代码时,默认情况下会打印表达式(除非它们是None
)。它正常工作。您只是返回一个值
如果希望显示该值,则需要执行以下操作之一:
print queue.minimum()
或
打印未捕获的返回值是大多数解释器的实用功能。您将在javascript控制台中看到相同的行为。请正确缩进代码并使用{}按钮对其进行格式化。因此,我需要为每个if语句插入打印语句以获得正确的输出?是的,这是正确的。或者在每个if语句中,您可以将返回值存储在变量中,如ret=queue.minimum()
,然后在最后一个if
语句之后print(ret)
。好的,很好。我不能再点击它4分钟,显然我没有足够的代表投票。。。但我感谢你的帮助
print queue.minimum()
rval = queue.minimum()
print rval