代码之家  ›  专栏  ›  技术社区  ›  Adam Nelson

Python类结构…prep()方法?

  •  0
  • Adam Nelson  · 技术社区  · 16 年前

    我们有一个元类、一个类和一个子类用于警报系统:

    class AlertMeta(type):
    """
    Metaclass for all alerts    
    Reads attrs and organizes AlertMessageType data
    """
    def __new__(cls, base, name, attrs):
        new_class = super(AlertMeta, cls).__new__(cls, base, name, attrs)
        # do stuff to new_class
        return new_class
    
    class BaseAlert(object):
    """
    BaseAlert objects should be instantiated
    in order to create new AlertItems.
    Alert objects have classmethods for dequeue (to batch AlertItems)
    and register (for associated a user to an AlertType and AlertMessageType)
    
    If the __init__ function recieves 'dequeue=True' as a kwarg, then all other
    arguments will be ignored and the Alert will check for messages to send
    """
    
    __metaclass__ = AlertMeta
    
    def __init__(self, **kwargs):
        dequeue = kwargs.pop('dequeue',None)
        if kwargs:
            raise ValueError('Unexpected keyword arguments: %s' % kwargs)
        if dequeue:
            self.dequeue()
        else:
            # Do Normal init stuff
    
    def dequeue(self):
        """
        Pop batched AlertItems
        """
        # Dequeue from a custom queue
    
    class CustomAlert(BaseAlert):
        def __init__(self,**kwargs):
            # prepare custom init data
            super(BaseAlert, self).__init__(**kwargs)
    

    我们希望能够创建BaseAlert(CustomAlert)的子类,使我们能够运行出列,并能够运行自己的类 __init__ 密码我们认为有三种方法可以做到这一点:

    1. 添加一个prep()方法,该方法在BaseAlert中返回True,并由 __初始化__ .Child类可以定义自己的prep()方法。
    2. 使dequeue()成为类方法——然而,dequeue()的许多功能都需要非类方法——因此我们也必须使这些类方法成为类方法。
    3. 创建一个新类来处理队列。这个类会扩展BaseAlert吗?

    有没有处理这种情况的标准方法?

    1 回复  |  直到 16 年前
        1
  •  0
  •   Adam Nelson    16 年前

    对于我们的特殊问题,我们将dequeue()作为一个类方法。