重新定义__init__

时间:2013-03-15 15:05:17

标签: python matplotlib

我有一个来自库的类,我想修改构造函数的行为。

我在做:

from library import TheClass

TheClass._original_init = TheClass.__init__

def f(self, *karg, **kargw):
  print "hello"
  self._original_init(*karg, **kargw)

TheClass.__init__ = f

这是正确的方法吗?我在这个具体案例中遇到了问题:

import matplotlib.pyplot as plt
from matplotlib import axes
from matplotlib.ticker import MultipleLocator

axes.Subplot._original_init = axes.Subplot.__init__ 

def f(self, *karg, **kargw):
    def add_minor_locator(axis, n = 5):
        ticklocs = axis.get_ticklocs()
        diff = ticklocs[1] - ticklocs[0]
        minorLocator = MultipleLocator(diff/float(n))
        axis.set_minor_locator(minorLocator)
    add_minor_locator(self.get_xaxis())
    add_minor_locator(self.get_yaxis())

    self._original_init(*karg, **kargw)

axes.Subplot.__init__ = f

fig, ax = plt.subplots(nrows=1, ncols=1)

我明白了:

  File "/usr/lib64/python2.7/site-packages/matplotlib/axes.py", line 1319, in get_xaxis
    return self.xaxis
AttributeError: 'AxesSubplot' object has no attribute 'xaxis'

1 个答案:

答案 0 :(得分:2)

您假设原始__init__已经运行; {/ 1>}只应在初始化完成后调用

self.get_xaxis()