简体   繁体   English

实例化子类python

[英]Instantiating a subclass python

Just a simple class definition withh subclasses to show inheritance 只是一个带有子类的简单类定义以显示继承

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

Instantiating a subclass 实例化一个子类

ThisBook = Book('Title', 'Author', 'ItemID')

ThisCD = CD('Title', 'Author', 'ItemID')

This is my problem here I don't understand why the ThisBook the object's attribute doesn't change from False its default value to True . 这是我的问题,我不明白为什么ThisBook对象的属性不会从默认值False更改为True

# Using A method
print(ThisBook.GetIsRequested())

ThisBook.IsRequested = True
print(ThisBook.GetIsRequested())

Thank you a reason to why this doesn't work would be helpful 谢谢您为什么这样做不起作用的原因会有所帮助

You probably meant to do 你可能想做

ThisBook.__IsRequested = True

which you can't do because of name mangling . 由于名称修改您不能做的。 You could write another setter. 您可以写另一个二传手。

But before you dive too deeply into writing a lot of getters and setters you should be aware that the pythonic way is to not use them. 但是,在您深入研究编写许多getter和setter之前,您应该意识到pythonic方法是不使用它们。 Or, if additional logic is required, to use the @property decorator . 或者,如果需要其他逻辑,则使用@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

and then 接着

ThisBook = Book('Title', 'Author', 'ItemID')
print(ThisBook.requested)
ThisBook.requested = True
ThisBook.onloan = True
print(ThisBook.duedate)

You can't access a field with 2 underscores prefix like that (see What is the meaning of a single- and a double-underscore before an object name? ). 您不能像这样访问带有2个下划线前缀的字段(请参阅对象名称前的单下划线和双下划线是什么意思? )。 You need to write a proper setter: 您需要编写一个合适的setter:

def SetIsRequested(self, val):
    self.__IsRequested = val

What you are experiencing is the typical silliness of dynamic languages. 您正在体验的是动态语言的典型愚蠢行为。 A field on class can be set w/o being declared and the interpreter can't help you by pointing out that you've just created a new field called "IsRequested" in your class. 可以在不声明的情况下设置类的字段,并且解释器无法指出您刚刚在类中创建了一个名为“ IsRequested”的新字段,因此无法为您提供帮助。 Saves you some typing but costs you in ability of your interpreter and IDE to prevent you from messing up. 为您节省了一些打字时间,但使您无法使用自己的解释器和IDE,从而使您陷入混乱。

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

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