如何解决AttributeError:类型对象“LibraryItem”没有属性“Book_Title”?

How to solve AttributeError: type object 'LibraryItem' has no attribute 'Book_Title'?

提问人:Pius0405 提问时间:7/12/2023 更新时间:7/12/2023 访问量:22

问:

运行这段代码后发生错误。它说“AttributeError:类型对象'LibraryItem'没有属性'Book_Title”。是否可以从派生类访问基类中定义的属性,例如从方法访问它?

import datetime

class LibraryItem:
    def __init__(self,t,a,i):
        self.__Title = t
        self.__Author = a
        self.__ItemID = i
        self.__OnLoan = False
        self.__DuteDate = datetime.date.today()

    def SetOnLoan(self,o):
        self.__OnLoan = o
    def SetDueDate(self,d):
        self.__DueDate = d

class Book(LibraryItem):
    def __init__(self,t,a,i):
        LibraryItem.__init__(self,t,a,i)
        self.__RequestedBy = 'people'

    def SetRequestedBy(self,r):
        self.__RequestedBy = r

    def GetRequestedBy(self):
        return self.__RequestedBy

    def PrintDetails(self):
        print(LibraryItem.__Title)

ThisBook = Book('Python','Tom','123')
ThisBook.PrintDetails()
Python

评论


答:

1赞 Maria K 7/12/2023 #1

这里有两点:

  1. 初始化基类 (LibraryItem) in ,我相信这应该以不同的方式完成(有关详细信息,请参阅问题__init__Book
  2. 类属性的隐私性,这是通过不同数量的下划线实现的(有关详细信息,请参阅问题)。基本上,两个未分数隐藏了该属性。

代码

import datetime

class LibraryItem:
    def __init__(self,t,a,i):
        self.__Title = t
        self.__Author = a
        self.__ItemID = i
        self.__OnLoan = False
        self.__DuteDate = datetime.date.today()

    def SetOnLoan(self,o):
        self.__OnLoan = o
    def SetDueDate(self,d):
        self.__DueDate = d
    
    def GetTitle(self):
        return self.__Title

class Book(LibraryItem):
    def __init__(self,t,a,i):
        super(Book, self).__init__(t,a,i)
        self.__RequestedBy = 'people'

    def SetRequestedBy(self,r):
        self.__RequestedBy = r

    def GetRequestedBy(self):
        return self.__RequestedBy

    def PrintDetails(self):
        print(self.GetTitle())

ThisBook = Book('Python','Tom','123')
ThisBook.PrintDetails()

产生输出:

Python

评论

1赞 Zero 7/12/2023
您的答案有效,但您已在此处将访问模式从私有更改为受保护。
1赞 Maria K 7/12/2023
更改了代码以改用单独的 getter。