【发布时间】:2021-10-08 22:30:12
【问题描述】:
目前在我有一系列将 API 请求 JSON 转换为对象的类的情况下。这些对象是根据我的数据库模式建模的。我认为我正在努力解决的部分是如何表示那些在我的数据库中由外键形成的实体关系。
以下类仅作为示例,实例变量对于我的应用程序架构有很大不同。
class Table(ABC):
def __init__(self):
# stuff
@abstractmethod
def validateSchema(self):
"""Validates the resources column values."""
pass
class ClassRoom(Table):
def __init__(self, id, location_id, location):
super().__init__()
self.id = id
self.location = Location(location_id, location)
def validateSchema(self):
# stuff
class Location(Table):
def __init__(self, id, location):
super().__init__()
self.id = id
self.location = location
def validateSchema(self):
# stuff
我关心的部分是当我创建一个与将该对象作为实例变量的类相同类型的对象时。
class ClassRoom(Table):
def __init__(self, id, location_id, location):
# Can I instantiate this class even if it inherits the same parent?
self.location = Location(location_id, location)
这在 OOP 中可以吗?有没有更好的方法来设计我的课程?
此外,这些类只是为发送到我的 API 的请求 JSON 定义的。它们的目的是促进列验证和其他一些目的。我希望在这些类中实现的具体验证来自另一个 Stackoverflow 帖子Flask sqlAlchemy validation issue with flask_Marshmallow。我不想在这里重新创建 SqlAlchemy。
【问题讨论】:
-
引用同级类并没有错。这两个对象是完全独立的。
-
好的,很高兴知道。那你觉得我的设计有问题吗?
-
好像没问题。但是为什么不是
def __init__(self, id, location):并在调用者中创建Location对象呢? -
按照您的操作方式,每个
Classroom都会引用不同的Location对象,即使它们实际上位于同一位置。
标签: python oop design-patterns