<p>我正在学习Python第4版,目前正在做本书第六部分的练习。我现在正在做的练习让我有点困惑,我希望我能得到一些指导来解决这个问题。你知道吗</p>
<p>这是我正在处理的提示。你知道吗</p>
<blockquote>
<p>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.)</p>
</blockquote>
<p>所以我现在真正感兴趣的是</p>
^{2}$
<p>我可以看到这里有一个很好的干涸的用途,它可以一举两得。但我只是不知道如何实现它。
我知道我应该做的是实现某种方法,截取操作,增加计数器并打印消息。但我不知道该怎么做。我的基本想法是</p>
<pre><code>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)
</code></pre>
<p>(注意:这不是我写的代码,这是边界伪代码来突出我想做的事情。)</p>
<p>我能在这里得到点帮助吗?请不要直截了当地给我答案,我想弄清楚这一点,提示远不止答案。:)</p>
<p>提示:</p>
<pre><code>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
</code></pre>