简体   繁体   English

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

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

I am currently trying to implement a python class that automatically synchronized with a NoSQL database with implicit buffering, quite to the image of the SLQAlchemy . 我目前正在尝试实现一个Python类,该类与具有隐式缓冲的NoSQL数据库自动同步,这与SLQAlchemy的图像相当。

In order to do this, I need to track attribute updates issued by the user and, on each attribute update, call functions that keep that object in synchronization with the database or buffer. 为此,我需要跟踪用户发布的属性更新,并在每次属性更新时调用使该对象与数据库或缓冲区保持同步的函数。

What is the best way of doing this in Python? 用Python做到这一点的最佳方法是什么? If it passes through __setattr__ and __delattr__ , how do I do it correctly, to avoid messing up with garbage collector? 如果它通过__setattr____delattr__ ,如何正确执行操作以避免与垃圾收集器混淆?

One way to do it (the way I would recommend) is to use descriptors . 一种方法(我建议的方法)是使用描述符

First you make a class for your properties, something like: 首先,为您的属性创建一个类,如下所示:

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.

And then in your class entity class you have something like this: 然后,在您的类实体类中,您将得到以下内容:

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

Of course in practice you may have multiple Property types. 当然,实际上,您可能具有多种属性类型。 My guess is that SQLAlchemy does something like this, where Column types are descriptors. 我的猜测是SQLAlchemy会执行类似的操作,其中列类型是描述符。

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

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