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

0 投票
1 回答
598 浏览
提问于 2025-04-15 21:09

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

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. 在BaseAlert中添加一个prep()方法,这个方法返回True,并且在__init__中被调用。子类可以定义它们自己的prep()方法。
  2. 把dequeue()变成一个类方法——不过,dequeue()做的很多事情需要非类方法,所以我们也得把那些变成类方法。
  3. 创建一个新的类来处理队列。这个类会继承BaseAlert吗?

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

1 个回答

0

对于我们这个特定的问题,我们把 dequeue() 这个方法变成了一个类方法。

撰写回答