【问题标题】:Handling Subclass / Superclass records extracted from a database in python处理从python中的数据库中提取的子类/超类记录
【发布时间】:2020-10-23 11:38:52
【问题描述】:

我有一个 python 应用程序和一个 postgresql 数据库,其中有两个相互关联的表:

“设备”存储有关设备类型信息的记录,例如描述、图片和 id 字段

“项目”存储有关单个设备项目的记录,例如序列号和 id 字段。

我为每一个都创建了一个类,目前有一个 get(id) 方法从数据库中检索数据并将其存储在类的实例中,以及 create() 和 update() 方法从类实例并将其存储在数据库中。

我想让“Item”成为“Equipment”的子类,这样当您访问“item.description”时,您可以获得设备的描述。我如何管理这个子类,例如对于许多“项目”实例,每个“设备”只有一个实例。

创建子类实例后,是否可以更改其父实例?

编辑:按要求在下面添加了类,Item类应该与Type Class有相同的方法

class Equipment:
def __init__(self, bookingid=None, description=None, category=None,
             replacementprice=None, forcelabel=None, image=None):
    """Class to hold Equipment Data"""
    self.id = None
    self.bookingid = bookingid
    self.description = description
    self.category = category
    self.replacementprice = replacementprice
    self.forcelabel = forcelabel
    self.image = image
    self.stamp = None

def get(self, equipmentid):
    """retrieve equipment from database"""
    data = itemops.getequipment(equipmentid)
    self.id = data[0]
    self.bookingid = data[1]
    self.description = data[2]
    self.category = data[3]
    self.replacementprice = data[4]
    self.forcelabel = data[5]
    self.image = io.BytesIO(data[6])
    self.stamp = data[7]

def create(self):
    """create type in database"""
    returned = itemops.createequipment(self)
    if returned is not None:
        self.id = returned[0]
        self.stamp = returned[1]
    return self.id

def update(self):
    """update equipment in database"""
    self.stamp = itemops.updateequipment(self)

def refresh(self):
    """Update equipment instance if necessary"""
    if self.stamp != itemops.getequipmentstamp(self.id):
        self.get(self.id)
        return True
    else:
        return False
class Item:
def __init__(self, equipmentid=None, barcode=None, serial=None):
    self.id = None
    self.equipmentid = equipmentid
    self.barcode = barcode
    self.serial = serial
    self.eventid = None
    self.out_noteid = None
    self.in_noteid = None
    self.temp = False
    self.stamp = None

【问题讨论】:

  • Item 类是否继承自 Equipment 类?你也可以发布你的课程吗?
  • @Adamantoisetortoise 添加了类,目前它没有继承,因为我不知道如何做我所描述的,但我想要它。

标签: python oop object


【解决方案1】:

首先,您需要在 Item 类(我猜是equipmentisd)中有一个引用 Equipment 属性 id 的属性。 然后您可以使用您的属性equipmentid 在您的数据库中查找id==equipmentid 所在的设备类的实例。 因此,您的 Item 类显示 Equipment 类的属性 description 的方法如下所示:

def display_equip_description(self):
        data = itemops.getequipment(self.equipmentid) # gets the Equipment instance which 'id' is equal to the specified 'equipmentid' (attribute of Item)
        return data.description # return the description of the specified instance.

【讨论】:

    猜你喜欢
    • 2021-11-26
    • 2011-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-27
    • 2021-09-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多