只是一个简单的类定义,其中包含显示继承的子类
import datetime
class LibaryItem: #The base class definition
def __init__(self, t, a, i): # initialiser method
self.__Title = t
self.__Author_Artist = a
self.__ItemID = i
self.__OnLoan = False
self.DueDate = datetime.date.today()
def GetTitle(self):
return(self.__Title)
# All other Get methods go here
def Borrowing(self):
self.__OnLoan = True
self.__DueDate = self.__DueDate + datetime.timedelta(weeks = 3)
def Returning(self):
self.OnLoan = False
def PrintDetails(self):
print(self.__Title, '; ', self.__Author_Artist,'; ',end='') # end='' Appends a space instead of a newline
print(self.__ItemID, '; ', self.__OnLoan,'; ', self.__DueDate)
class Book(LibaryItem):# A subclass definition
def __init__(self, t, a, i): # Initialiser method
LibaryItem.__init__(self, t, a, i)
# This statement calls the constructor for the base class
self.__IsRequested = False
self.__RequestBy = 0
def GetIsRequested(self):
return(self.__IsRequested)
class CD(LibaryItem):
def __init__(self, t, a, i): # Initialiser method
LibaryItem.__init__(self, t, a, i)
self.__Genre = ""
def GetGenre(self):
return(self.__Genre)
def SetGenre(self, g):
self.__Genre = g
实例化子类
ThisBook = Book('Title', 'Author', 'ItemID')
ThisCD = CD('Title', 'Author', 'ItemID')
这是我在这里的问题,我不明白为什么对象属性ThisBook
没有从False
默认值更改为True
.
# Using A method
print(ThisBook.GetIsRequested())
ThisBook.IsRequested = True
print(ThisBook.GetIsRequested())
谢谢你为什么这不起作用的原因会有所帮助
你可能打算这样做
ThisBook.__IsRequested = True
由于名称混乱,您无法做到这一点。你可以写另一个二传手。
但是在你深入编写大量 getter 和 setter 之前,你应该意识到 pythonic 的方式是不使用它们。或者,如果需要其他逻辑,请使用@property
修饰器。
class LibaryItem:
def __init__(self, title, author, itemid): # initialiser method
self.title = title
self.author = author
self.itemid = itemid
self._onloan = False
self.duedate = datetime.date.today()
@property
def onloan(self):
return self._onloan
@onloan.setter
def onloan(self, value):
if value:
self.duedate += datetime.timedelta(weeks = 3)
self._onloan = value
def __str__(self):
return "%s; %s; %s; %s; %s" % (self.title, self.author, self.itemid, self.onloan, self.duedate)
class Book(LibaryItem):
def __init__(self, title, author, itemid):
LibaryItem.__init__(self, title, author, itemid)
self.requested = False
self.requestby = 0
然后
ThisBook = Book('Title', 'Author', 'ItemID')
print(ThisBook.requested)
ThisBook.requested = True
ThisBook.onloan = True
print(ThisBook.duedate)
您不能像这样访问带有 2 个下划线前缀的字段(请参阅对象名称前的单下划线和双下划线是什么意思?你需要写一个合适的二传手:
def SetIsRequested(self, val):
self.__IsRequested = val
你正在经历的是动态语言的典型愚蠢。 可以在不声明的情况下设置类上的字段,解释器无法通过指出您刚刚在类中创建一个名为"IsRequest"的新字段来帮助您。 为您节省一些打字时间,但会花费您的解释器和 IDE 的能力,以防止您搞砸。