实现在属性upd上调用外部函数的Python类的正确方法

2024-05-03 18:55:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在尝试实现一个python类,该类自动与具有隐式缓冲的NoSQL数据库同步,非常类似于SLQAlchemy。你知道吗

为了做到这一点,我需要跟踪用户发出的属性更新,并且在每次属性更新时,调用使该对象与数据库或缓冲区保持同步的函数。你知道吗

在Python中最好的方法是什么?如果它经过__setattr____delattr__,我该如何正确地执行它,以避免与垃圾收集器发生冲突?你知道吗


Tags: 对象方法函数用户数据库属性垃圾收集器
1条回答
网友
1楼 · 发布于 2024-05-03 18:55:13

一种方法(我推荐的方法)是使用descriptors。你知道吗

首先,为属性创建一个类,例如:

class Property:
    def __init__(self, *args, **kwargs):
        #initialize the property with any information it needs to do get and set
    def __get__(self,obj, type=None):
        #logic to get from database or cache

    def __set__(self,obj, value):
        #logic to set the value and sync with database if necessary.

然后在你的类实体类中你有这样的东西:

class Student:
    student_id = Property(...)
    name = Property(...)
    classes = Property(...)

当然,在实践中,您可能有多种属性类型。我猜SQLAlchemy是这样做的,其中列类型是描述符。你知道吗

相关问题 更多 >