繁体   English   中英

在Python中访问集合类属性

[英]Accessing collection class attributes in Python

我在Python 3.6中工作,并且有两个类,一个类充当另一个列表的容器,但是嵌套类不从高阶类继承。 基本上,这是我正在查看的内容的简化:

class Library():

    def __init__(self, name, bookList):
        """
        Initializes a library class object
        Send: self (Library object), name (str), list of books in the library (list of Book objects)    
        """
        self.name=name
        self.bookList=bookList

class Book():
    def __init__(self, title, author, year):
        """
        Initializes a book class object
        Send: self (Book object), title (str), author (str), year (int)
        """
        self.title=title
        self.author=author
        self.year=year

    def owningLibrary(self):
        """
        Identifies the name of the library that owns the book
        Send: self (Book object)
        """
        #some code that looks at the library's name and returns it

if __name__=="__main__":

    #Create book
    warAndPeace = Book("War and Peace", "Tolstoy, Leo", 1869)
    hitchhikersGuide = Book("Hitchhiker's Guide to the Galaxy, The", "Adams, Douglas", 1985)

    #Create library
    orangeCountyLibrary = Library("Orange County Public Library", [warAndPeace, hitchhikersGuide])

    #Print the current owner of Hitchhiker's Guide
    print(hitchhikersGuide.owningLibrary())

我的问题是:如何使包含的对象(书)能够访问容器对象(库)的属性/方法。 在我的示例中:返回所属库的“名称”变量

我考虑过的尝试:

  • Inheritance + super()-但是书籍不是图书馆的子类,图书馆只是包含书籍
  • 维护每个书本对象的库特征-但这似乎很笨拙,并且会在库和书本对象之间重复数据

我敢肯定,我显然缺少某些东西,但是我搜索的所有内容似乎都带有关于继承的建议,这对我来说似乎没有任何意义。 谢谢你的帮助!

添加到Book.__init__

self.library = None

添加到owningLibrary

if self.library is None:
    return "No Library"
return self.library.name

添加到Library.__init__

for book in self.bookList:
    book.library = self

如果没有具有指示属性的属性,则Book无法知道它所在的Library 然后,“图书馆”实例需要告诉所有书籍,哪个图书馆包含这些书籍。

由于“ LibraryBook在“定义方面”是独立的,因此您必须从book显式创建对library的引用。

一种解决方案是在Book类中添加library字段,该字段将存储库的名称(或对Library对象的引用,取决于您计划进一步执行的操作)。 这可以在Library __init__

class Library:
    def __init__(self, name, book_list):
        """
        Initializes a library class object
        Send: self (Library object), name (str), list of books in the library (list of Book objects)    
        """
        self.name = name
        self.bookList = book_list
        # set reference to the name of this library for every added book
        for book in book_list:
            book.library = self.name


class Book:
    def __init__(self, title, author, year):
        """
        Initializes a book class object
        Send: self (Book object), title (str), author (str), year (int)
        """
        self.title = title
        self.author = author
        self.year = year
        self.library = None  # book does not belong to any library yet


if __name__ == "__main__":
    # Create book
    warAndPeace = Book("War and Peace", "Tolstoy, Leo", 1869)
    hitchhikersGuide = Book("Hitchhiker's Guide to the Galaxy, The", "Adams, Douglas", 1985)

    # Create library
    orangeCountyLibrary = Library("Orange County Public Library", [warAndPeace, hitchhikersGuide])

    # Print the current owner of Hitchhiker's Guide
    print(hitchhikersGuide.library)  # Orange County Public Library

如果一Book可能同时位于多个库中:

  • 初始化self.libraries = []而不是self.library = None ;
  • Library构造函数中,执行book.libraries.append(self.name)而不是book.library = self.name

我这样做的方式是:

    class Library:
        def __init__(self, name):
            self.name=name
            self.books=[]
    class Book:
        def __init__(self, title, author, year, library):
            self.title=title
            self.author=author
            self.year=year
            self.library=library
            self.library.books.append(self)#put this book in the library
    # Create library
    orangeCountyLibrary = Library("Orange County Public Library"
    # Create book
    warAndPeace = Book("War and Peace", "Tolstoy, Leo",
    1869,orangeCountyLibrary)
    hitchhikersGuide = Book("Hitchhiker's Guide to the Galaxy, The",
    "Adams, Douglas", 1985,orangeCountyLibrary)
    # Print the current owner of Hitchhiker's Guide
    print(hitchhikersGuide.library)  # Orange County Public Library
这是tkinter处理将Canvas实例连接到Tk实例的方式。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM