0

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

我在做:

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'
4

1 回答 1

2

您假设原始__init__版本已经运行;self.get_xaxis()只应在初始化发生后调用:

def f(self, *karg, **kargw):
    _original_init(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())
于 2013-03-15T15:13:54.543 回答