只是一个简单的类定义,带有h个子类来显示继承
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
实例化子类
^{pr2}$这就是我的问题,我不明白为什么ThisBook
对象的属性没有从False
的默认值改为True
。在
# Using A method
print(ThisBook.GetIsRequested())
ThisBook.IsRequested = True
print(ThisBook.GetIsRequested())
谢谢你能解释一下为什么这不起作用
你可能是故意的
因为name mangling,你不能这样做。你可以再写一个setter。在
但是在你深入写很多getter和setter之前,你应该意识到python的方法是不要使用它们。或者,如果需要其他逻辑,则使用^{} decorator 。在
^{pr2}$然后呢
不能像这样访问前缀为2下划线的字段(请参见What is the meaning of a single- and a double-underscore before an object name?)。 你需要写一个合适的setter:
你所经历的是动态语言的典型愚蠢。类上的字段可以在不声明的情况下设置,并且解释器无法帮助您指出您刚刚在类中创建了一个名为“IsRequested”的新字段。为您节省了一些输入,但会降低您的解释器和IDE的能力,以防止您出错。在
相关问题 更多 >
编程相关推荐