繁体   English   中英

实现在属性更新时调用外部函数的Python类的正确方法

[英]Correct way of implementing a Python class that calls external functions on attribute update

我目前正在尝试实现一个Python类,该类与具有隐式缓冲的NoSQL数据库自动同步,这与SLQAlchemy的图像相当。

为此,我需要跟踪用户发布的属性更新,并在每次属性更新时调用使该对象与数据库或缓冲区保持同步的函数。

用Python做到这一点的最佳方法是什么? 如果它通过__setattr____delattr__ ,如何正确执行操作以避免与垃圾收集器混淆?

一种方法(我建议的方法)是使用描述符

首先,为您的属性创建一个类,如下所示:

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会执行类似的操作,其中列类型是描述符。

暂无
暂无

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

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