在Python

时间:2017-12-29 18:49:48

标签: python python-3.x class attributes containers

我在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() - 但书籍不是图书馆的子类,图书馆只包含图书
  • 维护每个图书对象的图书馆特征 - 但这看起来很笨重,并且在图书馆和图书对象中复制数据

我确定有一些明显的东西我不知道,但我搜索过的所有东西似乎都回来了继承的建议,这对我来说似乎没有意义。谢谢你的帮助!

3 个答案:

答案 0 :(得分: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无法知道它是什么<div class="page1"> <img src="img/LogoEpaissiBlanc.png" alt="Logo" id="logoindex1"> </div> 。然后,Library实例需要告诉所有书籍哪些库包含它们。

答案 1 :(得分:0)

由于LibraryBook是&#34;定义明智&#34;如果是独立的,您必须明确地从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

答案 2 :(得分: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
这是tkinter处理将Canvas实例连接到Tk实例的方式。