在Python中访问集合类属性

问题描述 投票:0回答:3

我在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())

我的问题是:如何启用包含的对象(书)来访问容器对象(库)的属性/方法。在我的示例中:返回拥有库的“name”变量

我考虑过的尝试:

  • 继承+ super() - 但书籍不是库的子类,库只包含书籍
  • 在每个书籍对象上维护库特征 - 但这看起来很笨重,并且在库和书籍对象之间复制数据

我确信有一些显而易见的东西让我失踪了,但我搜索过的所有东西似乎都回来了,对我来说似乎没有意义的继承建议。谢谢你的帮助!

python python-3.x class attributes containers
3个回答
1
投票

添加到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是什么。然后,Library实例需要告诉所有书籍哪些库包含它们。


0
投票

由于LibraryBook是“定义明智的”独立的,你必须明确地从library创建一个book的引用。

一种解决方案可能是将library字段添加到Book类中,该类将存储库的名称(或对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

0
投票

我这样做的方式是:

    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
this is the way tkinter handles connecting Canvas instances to Tk instances.
© www.soinside.com 2019 - 2024. All rights reserved.