简体   繁体   English

在Python中访问集合类属性

[英]Accessing collection class attributes in Python

I am working in Python 3.6 and have two classes, one class serves as a container for a list of the other, but the nested class does not inherit from the higher-order class. 我在Python 3.6中工作,并且有两个类,一个类充当另一个列表的容器,但是嵌套类不从高阶类继承。 Basically here is a simplification of what I'm looking at: 基本上,这是我正在查看的内容的简化:

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

My question is: How do I enable the contained object (book) to access the attributes/methods of the container object(library). 我的问题是:如何使包含的对象(书)能够访问容器对象(库)的属性/方法。 In my example: to return the "name" variable of the owning library 在我的示例中:返回所属库的“名称”变量

What I've considered trying: 我考虑过的尝试:

  • Inheritance+super() - but books aren't subclasses of libraries, libraries simply contain books Inheritance + super()-但是书籍不是图书馆的子类,图书馆只是包含书籍
  • Maintaining library characteristics on each book object - but this seems clunky and duplicates data across the library and book objects 维护每个书本对象的库特征-但这似乎很笨拙,并且会在库和书本对象之间重复数据

I'm sure there is something obvious that I'm missing, but everything I've searched for seems to come back with recommendations for inheritance which doesn't seem to make sense to me. 我敢肯定,我显然缺少某些东西,但是我搜索的所有内容似乎都带有关于继承的建议,这对我来说似乎没有任何意义。 Thanks for your help! 谢谢你的帮助!

Add to Book.__init__ : 添加到Book.__init__

self.library = None

Add to owningLibrary : 添加到owningLibrary

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

Add to Library.__init__ : 添加到Library.__init__

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

There is no way for the Book to know what Library it's in without it having an attribute that tells it. 如果没有具有指示属性的属性,则Book无法知道它所在的Library The Library instance then needs to tell all of the books what library contains them. 然后,“图书馆”实例需要告诉所有书籍,哪个图书馆包含这些书籍。

Since Library and Book are "definition-wise" independent, you have to create a reference to a library from a book explicitly. 由于“ LibraryBook在“定义方面”是独立的,因此您必须从book显式创建对library的引用。

One solution could be to add library field to the Book class, which will store the name of a library (or reference to Library object, depends on what you plan to do further). 一种解决方案是在Book类中添加library字段,该字段将存储库的名称(或对Library对象的引用,取决于您计划进一步执行的操作)。 That can be done in the Library __init__ : 这可以在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

If it is possible for a Book to be in multiple libraries at the same time: 如果一Book可能同时位于多个库中:

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

the way i would do this is: 我这样做的方式是:

    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. 这是tkinter处理将Canvas实例连接到Tk实例的方式。

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

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