如何通过子类化拦截操作?

2024-06-28 11:17:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习Python第4版,目前正在做本书第六部分的练习。我现在正在做的练习让我有点困惑,我希望我能得到一些指导来解决这个问题。你知道吗

这是我正在处理的提示。你知道吗

Subclassing. Make a subclass of MyList from exercise 2 called MyListSub, which extends MyList to print a message to stdout before each overloaded operation is called and counts the number of calls. MyListSub should inherit basic method behavior from MyList. Adding a sequence to a MyListSub should print a message, increment the counter for + calls, and perform the superclass’s method. Also, introduce a new method that prints the operation counters to stdout, and experiment with your class interactively. Do your counters count calls per instance, or per class (for all instances of the class)? How would you program the other option)? (Hint: it depends on which object the count members are assigned to: class members are shared by instances, but self members are per-instance data.)

所以我现在真正感兴趣的是

^{2}$

我可以看到这里有一个很好的干涸的用途,它可以一举两得。但我只是不知道如何实现它。 我知道我应该做的是实现某种方法,截取操作,增加计数器并打印消息。但我不知道该怎么做。我的基本想法是

def count_ops(self, op_count):
    # intercept calls to operator overloading methods
    op_count += 1
    print 'Number of calls to operator {0}: {1}'.format(oper, op_count)

(注意:这不是我写的代码,这是边界伪代码来突出我想做的事情。)

我能在这里得到点帮助吗?请不要直截了当地给我答案,我想弄清楚这一点,提示远不止答案。:)


Tags: andofthetocountmethodareclass
3条回答

除了计算调用之外,你的重载方法还做了什么?换句话说,你一定要写吗?如果是的话,可以使用decorator,或者只使用一个单独的函数,比如一个函数,并从每个方法调用它。你知道吗

如果子类中唯一需要的重载是计数,那么可以查看^{}。需要注意的是,它有点复杂,在您将它用于生产代码之前,您需要对它有一个透彻的理解。其他选项包括class decoratormetaclass来包装您关心的每个方法。你知道吗

提示:

def count(cls):
    for attr in (attr for attr in dir(cls) if not attr.startswith('_')):
        method = getattr(cls,attr)
        if callable(method):
            setattr(cls,attr,func_count(method,attr))
    return cls

相关问题 更多 >