Python类结构... prep()方法?

时间:2010-04-02 14:44:10

标签: python

我们有一个警报系统的元类,类和子类:

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)的子类,它们允许我们运行dequeue并能够运行自己的__init__代码。我们认为有三种方法可以做到这一点:

  1. 添加一个prep()方法,该方法在BaseAlert中返回True并由__init__调用。子类可以定义自己的prep()方法。
  2. 使dequeue()成为一个类方法 - 但是,很多dequeue()确实需要非类方法 - 所以我们也必须制作这些类方法。
  3. 创建一个用于处理队列的新类。这个类会扩展BaseAlert吗?
  4. 是否有处理此类情况的标准方法?

1 个答案:

答案 0 :(得分:0)

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