【发布时间】:2018-10-28 09:29:59
【问题描述】:
目标
我正在尝试创建一个练习脚本,该脚本存储一个可以添加新项目的菜单。
这些项目是诸如“战斗动画”、“文本速度”或“字幕”之类的东西。
菜单会像这样打印出它的所有项目
(注意所有项目的间距都调整为适合最大的一个)
| border color || (black) blue red green || Text Speed || slow (medium) fast |
图 1
我的方法 MenuItem 本身就是一个类。它管理菜单项的内容并存储打印时需要多少调整空间。
这个类本身就可以很好地工作。如果上述两项是单独使用 MenuItem 类方法创建和打印的,它们将如下所示:
| border color || (black) blue red green || Text Speed || slow (medium) fast |
图2
Menu 是我创建的一个类,用于存储菜单项并调整它们的间距值,以便它们像图 1 一样打印。
我的代码
此代码已简化为仅显示可重现的错误。不包括值列表(黑色、蓝色、红色、绿色等)。
#!/usr/bin/env python3
class Menu(object):
class MenuItem(object):
def __init__(self, propertyTitle):
self.title = propertyTitle
self.printsize = (len(self.title)+4)
def printMenuItem(self):
f_indent = 2;
f_title = ((' '*f_indent)+ self.title.ljust(self.printsize-f_indent))
print('|',f_title ,'|',sep='')
def __init__(self):
self.width = 0;
self.items = [];
def addItem(self, pTitle):
f_menuItem = Menu.MenuItem(pTitle)
if(f_menuItem.printsize < self.width):
#if(f_menuItem.printsize < 5):
#adjusting padding on the smaller new menu item
f_menuItem.printsize = self.width
elif(f_menuItem.printsize > self.width):
#elif(f_menuItem.printsize > 5):
#adjusting padding on all past menu items to fit this new big item
self.width = f_menuItem
for x in self.items:
x.printsize = self.width
self.items.append(f_menuItem)
def printMenu(self):
for x in self.items:
x.printMenuItem()
print()
property_1_title = "border color";
property_2_title = "text speed";
myMenu = Menu()
#myMenu.items.append(myBorderColor)
#myMenu.items.append(myTextSpeed)
myMenu.addItem(property_1_title);
myMenu.addItem(property_2_title);
myMenu.printMenu()
问题
我收到以下错误:
line 20, in addItemif(f_menuItem.printsize < self.width):TypeError: '<' not supported between instances of 'int' and 'MenuItem'line 24, in printMenuItemf_title = ((' '*f_indent)+ self.f_title.ljust(self.printsize-f_indent))TypeError: unsupported operand type(s) for -: 'MenuItem' and 'int'
由于某种原因,python 将 MenuItem 的类属性(它们是整数)解释为 MenuItem 本身的类实例。
至少我是这样解释错误的。
这个错误的奇怪之处在于,这只发生在 Menu 类的方法在其内部存储的 MenuItem 实例上调用 MenuItem 方法时。
正如我之前提到的,当 MenuItem 类是唯一定义和使用的类时,不会发生这些错误。
(MenuItem 是定义为 Menu 中的一个类还是在 Menu 之前定义为一个单独的类也没关系。同样的错误也会发生)
我的问题
为什么 python 将 f_menuItem.printsize 和 self.printsize 解释为 MenuItems 而不是整数?
我可能会想出一种不同的方式来构建程序以避免这种情况。但这只是一个练习脚本。我真的很想知道造成此错误的原因。
【问题讨论】:
-
self.width = f_menuItem? -
您明确地将
MenuItem对象分配给self.width。你甚至调用变量f_menuItem...f_menuItem = Menu.MenuItem(pTitle)然后self.width = f_menuItem。顺便说一句,你为什么要在这里使用嵌套类? -
@juanpa.arrivillaga
self.width = f_menuItem是我未完成的声明。如果您看到实际类具有的其余属性和方法,则类结构会更有意义。我承认嵌套类在上面的代码中看起来很傻。
标签: python class typeerror python-3.6 class-attributes