簡體   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