首页 > 解决方案 > 嵌套类属性未被识别为 int

问题描述


正在尝试创建一个练习脚本,该脚本存储一个可以添加新项目的菜单。这些项目是诸如“战斗动画”、“文本速度”或“字幕”之类的东西。菜单将像这样打印出所有项目(注意所有项目的间距都调整为适合最大的项目)

| 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 addItem
if(f_menuItem.printsize < self.width):
TypeError: '<' not supported between instances of 'int' and 'MenuItem'

line 24, in printMenuItem
f_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 解释为 MenuItemsf_menuItem.printsizeself.printsize不是 ints?
我可能会想出一种不同的方式来构建程序以避免这种情况。但这只是一个练习脚本。我真的很想知道发生了什么来创建这个错误。

标签: pythonclasstypeerrorpython-3.6class-attributes

解决方案


您的问题出在 addItem() 中,特别是包含该行的 if 语句的 elif 分支:self.width = f_menuItem这会破坏 self.width 在第一次调用 addIem 时将其从 int 更改为 MenuItem。因此,当第二次调用 addItem 时,比较就会失败。


推荐阅读