【问题标题】:python inner classes how to createpython内部类如何创建
【发布时间】:2018-10-01 20:11:50
【问题描述】:

我正在尝试创建一个名为 My_Axes 的类。它有一个模块“大小”,它以图形的大小、nx、ny - 多少个图和共享 -(真或假)作为参数,无论我是否想共享 X 轴。

然后有一个内部类叫做:'Style'。它旨在改变 My_Axes.size() 返回的轴的外观。在这种情况下,我的目标是像看起来细轴和 Helvetica 字体的 matlab。下面是我的代码。请原谅我,因为我还在学习 python。

class My_Axes:

       def __init__(self):

              self.style = self.Style()

       def size(self,fig_siz,nx,ny,share):
              import matplotlib.pyplot as plt
              from matplotlib.ticker import MaxNLocator 
              import numpy as np 


              self.fig_siz=fig_siz
              self.nx = nx
              self.ny = ny
              self.share = share


              fig = plt.figure(figsize = self.fig_siz)
              x, y = self.fig_siz


              self.nax = {}
              self.n = 0
              for i in range(self.nx):
                     for j in range(self.ny):
                            if self.share:
                                   width = (0.9/self.nx)
                                   height =(0.9/self.ny)
                                   xpos = 0.08 + i*width
                                   ypos = 0.08 + j*height
                                   a = fig.add_axes([xpos,ypos,width,height])
                                   self.nax['ax'+str(self.n)] = a


                                   if j > 0: self.nax['ax'+str(self.n)].set_xticklabels([])
                                   if i > 0: self.nax['ax'+str(self.n)].set_yticklabels([])
                                   self.nax['ax'+str(self.n)].yaxis.set_major_locator(MaxNLocator(prune='lower'))
                                   self.nax['ax'+str(self.n)].xaxis.set_major_locator(MaxNLocator(prune='lower'))
                                   self.n += 1
                            else:
                                   width = ((0.6+(x+y)/180.)/self.nx)
                                   height =((0.6+(x+y)/180.)/self.ny)
                                   xpos = 0.08 + (width  + 0.1)*i
                                   ypos = 0.08 + (height + 0.1)*j
                                   a = fig.add_axes([xpos,ypos,width,height])
                                   self.nax['ax'+str(self.n)] = a
                                   self.n += 1

                            axx = self.nax       
              return axx

       class Style:

              def __init__(self,axx):
                     self.nax = axx

              def matlb(self):

                     from matplotlib import rc, font_manager


                     ticks_font = font_manager.FontProperties(family='Helvetica', style='normal',
                     size=12, weight='normal', stretch='normal')
                     for a in sorted(self.nax):
                            aax = self.nax[a].xaxis
                            aay = self.nax[a].yaxis

                     for axis in ['bottom','left']:
                            self.nax[a].spines[axis].set_linewidth(0.3)

                     for axis in ['right','top']:
                            self.nax[a].spines[axis].set_visible(False)
                     aax.set_ticks_position('bottom')
                     aay.set_ticks_position('left')

                     lsiz = 8 + 4./self.n
                     self.nax[a].xaxis.set_tick_params(labelsize=lsiz)
                     self.nax[a].yaxis.set_tick_params(labelsize=lsiz)
                     return self.nax

#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@


aax = My_Axes().size((8,8),3,3,True)


aax.style.matlb

当我运行代码时,我收到了错误:

Traceback (most recent call last):
  File "/Users/aya/Desktop/test_class2.py", line 103, in <module>
    aax = My_Axes().size((8,8),3,3,True)
  File "/Users/aya/Desktop/test_class2.py", line 23, in __init__
    self.style = self.Style()
TypeError: __init__() takes exactly 2 arguments (1 given)
[Finished in 0.5s with exit code 1]
[shell_cmd: python -u "/Users/aya/Desktop/test_class2.py"]
[dir: /Users/aya/Desktop]
[path: /usr/local/opt/coreutils/libexec/gnubin:/usr/local/bin:/bin:/usr/bin:/usr/sbin:/usr/local/sbin:/bin:/sbin:/Library/TeX/texbin:/opt/X11/bin]

【问题讨论】:

  • 你应该看看 Python 编码指南,又名PEP8。您的代码有点难以阅读。
  • @Laurent LAPORTE 对此我很抱歉,但感谢您的建议并附上该链接。
  • 注意,size 是一个函数,一个方法,而不是一个模块。另外,为什么要使用内部类?

标签: python class inner-classes


【解决方案1】:

您的异常正在发生,因为 Style 类没有一个构造函数,该构造函数接受零个非self 参数,这是您在代码底部调用 aax = My_Axes()... 时要查找的内容。

问题出现在您调用self.style = self.Style() 的行上。

如果您确实想在那里创建Style 对象,则需要编辑My_Axes 构造函数,以便将有效的axx 参数传递给self.Style(axx) 调用,例如:

class My_Axes:

       def __init__(self, fig_siz,nx,ny,share):
              axx = self.size(fig_siz,nx,ny,share)
              self.style = self.Style(axx)

       # ...

       class Style:
              def __init__(self, axx):
                     # ...
#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

aax = My_Axes((8,8),3,3,True)

aax.style.matlb()

【讨论】:

  • 非常感谢!你知道在 My_Axes 类下创建 axx 时如何将它传递给 self.Style() 吗?
  • @user3578925 我添加了一些示例代码,希望能回答您的问题
  • 它可能在aax.set_ticks_position('bottom') 上中断,因为在该行发生之前没有定义aax。我猜这是因为 for a in sorted(self.nax): 没有迭代任何东西。
  • 真的,您可能希望将for axis in ['bottom','left']:self.nax[a].yaxis.set_tick_params(labelsize=lsiz) 之间的所有内容再缩进一次,以便它们位于for a in sorted(self.nax): 块内。
  • 非常感谢。你在写。 axx 没有被引用,因为我出于某种原因缩进了 return 语句。我接受你的答案是正确的。
猜你喜欢
  • 2012-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-11
  • 1970-01-01
  • 2011-06-19
相关资源
最近更新 更多