嵌套的 class 属性未被识别为 int

Nested class attribute isn't being recognized as int

目标
我正在尝试创建一个练习脚本来存储一个可以添加新项目的菜单。 这些项目是 "battle animation"、"text speed" 或 "subtitles" 之类的东西。 菜单会像这样打印出它的所有项目 (注意所有项目的间距都已调整以适应最大的项目)

| border color |
| (black) blue red green |
| Text Speed |
| slow (medium) fast |
图 1

我的方法
MenuItem本身就是一个class。它管理菜单项的内容并存储打印时需要多少调整space。 这个 class 本身工作得很好。如果以上两项是单独使用 MenuItem class 方法创建和打印的,它们将如下所示: | border color |
| (black) blue red green |
| Text Speed |
| slow (medium) fast |
图 2

Menu 是我用来存储菜单项并调整它们的间距值的 class,因此它们将像图 1 一样打印。

我的代码
此代码已缩减为仅显示可重现的错误。不包括值列表(黑色、蓝色、红色、绿色等)。
#!/usr/bin/envpython3

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 的 class 属性(整数)解释为 MenuItem 本身的 class 个实例。 至少我是这样解释错误的。
这个错误的奇怪之处在于,只有当 Menu class 的方法在其内部存储的 MenuItem 实例上调用 MenuItem 方法时才会发生。
正如我之前提到的,当 MenuItem class 是唯一定义和使用的 class 时,这些错误不会发生。
(同样,MenuItem 是在 Menu 中定义为 class 还是在 Menu 之前定义为单独的 class 也没有关系。同样的错误也会发生)

我给你的问题

为什么 python 将 f_menuItem.printsizeself.printsize 解释为菜单项而不是整数?
我可能可以想出一种不同的方法来构建程序来避免这种情况。但这只是一个练习脚本。我真的很想知道造成此错误的原因。

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