0

Error occurs after running this piece of code. It says "AttributeError: type object 'LibraryItem' has no attribute 'Book_Title". Can an attribute defined in base class be accessed from derived class such as accessing it from a method?

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

1 Answers1

1

There're 2 points here:

  1. initialization of a base class (LibraryItem) in __init__ of Book, which should be done sligthly differently I believe (see question for details)
  2. the privacy of class attributes, which is achieved by different number of underscores (see question for details). Basically two undescores hide the attribute.

The code

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

Produces output:

Python
Maria K
  • 1,491
  • 1
  • 3
  • 14