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

时间:2017-01-25 12:47:40

标签: python python-2.7 class

所以这让我困惑了几天,我有三个叫做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)

该部分还列出了所有儿童笔记。这一切都通过一个 Book 类对象进行管理:

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个子页面,如果我打印出每个部分已添加到每个部分的页面名称。< / p>

我非常感谢任何人能够发现我的愚蠢错误。

提前致谢! :)

1 个答案:

答案 0 :(得分:1)

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

class Section:

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

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