小编Hay*_*don的帖子

如何在添加到类中的方法中访问"__"(双下划线)变量

背景

我希望使用元类来添加基于原始类的辅助方法.如果我希望添加的方法使用,self.__attributeName我得到一个AttributeError(因为名称修改)但是对于现有的相同方法,这不是问题.

代码示例

这是一个简化的例子

# Function to be added as a method of Test
def newfunction2(self):
    """Function identical to newfunction"""
    print self.mouse
    print self._dog
    print self.__cat

class MetaTest(type):
    """Metaclass to process the original class and
    add new methods based on the original class
    """
    def __new__(meta, name, base, dct):
        newclass = super(MetaTest, meta).__new__(
                meta, name, base, dct
                )

        # Condition for adding newfunction2
        if "newfunction" in dct:
            print "Found newfunction!"
            print "Add newfunction2!"
            setattr(newclass, "newfunction2", newfunction2) …
Run Code Online (Sandbox Code Playgroud)

python metaprogramming class

9
推荐指数
1
解决办法
6245
查看次数

防止GridSpec子图分离随图形大小而变化

我想创建一个没有中间空间的图形网格.

看起来像这样:

在此输入图像描述

代码1

import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec

fig = plt.figure()

gs = GridSpec(2, 2, wspace=0.0, hspace=0.0)

ax1 = fig.add_subplot(gs[0, 0])
ax2 = fig.add_subplot(gs[0, 1])
ax3 = fig.add_subplot(gs[1, 0])
ax4 = fig.add_subplot(gs[1, 1])

fig.show()
Run Code Online (Sandbox Code Playgroud)

但是,当我添加数据时,子图之间的间距取决于图的尺寸.(通过改变fig.show()打开的窗口的尺寸可以看出.)

举个例子:

在此输入图像描述

代码2

import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec

import numpy as np

fig = plt.figure()

gs = GridSpec(2, 2, wspace=0.0, hspace=0.0)

ax1 = fig.add_subplot(gs[0, 0])
ax2 = fig.add_subplot(gs[0, 1])
ax3 = fig.add_subplot(gs[1, 0])
ax4 = fig.add_subplot(gs[1, 1])

for axis in …
Run Code Online (Sandbox Code Playgroud)

python plot matplotlib python-2.7

5
推荐指数
1
解决办法
4686
查看次数

标签 统计

python ×2

class ×1

matplotlib ×1

metaprogramming ×1

plot ×1

python-2.7 ×1