问题:从另一个类的方法中创建类对象,并将它们添加到Python列表中

2024-06-02 08:48:04 发布

您现在位置:Python中文网/ 问答频道 /正文

这让我困惑了好几天,我有三门课,一门叫做Page

class Page:

   def __init__(self, pageName, sectionIBelongTo="Uncategorised"):
        self.mySection = sectionIBelongTo
        #each page belongs to only one section
        self.name = pageName

必须具有指定的对象:

class Section:

    childPages = []

    def __init__(self, padName):
        self.name = padName

    def addSection(self, pageObject):
        self.childPages.append(pageObject)

节还列出了所有子注释。所有这些都通过一个图书类对象进行管理:

class Book:
    Sections = []

    def __init__(self):
        print "notebook created"

    def addSection(self, secName):
        sectionToAdd = Section(secName)

        self.Sections.append(sectionToAdd)

    def addPage(self, bufferPath, pageName, pageSection="Uncategorised"):
        #Create a page and add it to the appropriate section


        for section in self.Sections:
            if section.name == pageSection:
                sectionToSet = section
        #Search list of sections for matching name.

        newPage = Page(pageName, sectionToSet)
        #Create new page and assign it the appropriate section object

        self.Sections[self.Sections.index(sectionToSet)].addSection(newPage)
        #Add page to respective section's list of pages.

如您所见,它包含所有部分的列表。因此,我从另一个文件导入这些类,并尝试像这样填充我的书:

myBook = Book()

myBook.addSection("Uncategorised")
myBook.addSection("Test")
myBook.addSection("Empty")
#Create three sections

myBook.addPage("belongs to uncategorised")
#Add page with no section parameter (uncategorised).
myBook.addPage("Belongs to test", "Test")
#Add page to section "Test"
myBook.addPage("Belongs to uncategorised again")
#Another uncategorised page

for x in range(0, 3):
    print "Populated section '", myBook.Sections[x].name, "', with: ", len(myBook.Sections[x].childPages), " child pages."

输出显示所有三个部分都创建得很好,但是每个部分都有3个子页面,如果我打印页面名称,似乎每个页面都已添加到每个部分

如果有人能发现我愚蠢的错误,我将不胜感激

提前感谢!:)


Tags: tonameselfinitdefpagesectionclass
1条回答
网友
1楼 · 发布于 2024-06-02 08:48:04

使childPages成为实例属性而不是类属性,应该可以解决您的问题:

class Section:

    def __init__(self, padName):
        self.name = padName
        self.childPages = []

    def addSection(self, pageObject):
        self.childPages.append(pageObject)

相关问题 更多 >