我有一个类,有方法来构建一些图。我尝试在一个图上显示不同的图。最后一个图总是覆盖图的属性(标题,图例......)。我希望如果我的方法中有return
,那么行为将与没有它的方法不同,但似乎不是真的。
我想弄清楚return
有什么区别。用来说明我的问题的代码是:
import matplotlib.pyplot as plt
import numpy as np
class myClass1(object):
def __init__(self):
self.x = np.random.random(100)
self.y = np.random.random(100)
def plotNReturn1(self):
plt.plot(self.x,self.y,'-*',label='randNxy')
plt.title('Plot No Return1')
plt.legend(numpoints = 1)
def plotNReturn2(self):
plt.plot(self.y,self.x,'-x',label='randNzw')
plt.title('Plot No Return2')
plt.legend(numpoints = 2)
def plotWReturn1(self):
fig = plt.plot(self.x,self.y,'-*',label='randWxy')
fig = plt.title('Plot With Return1')
fig = plt.legend(numpoints = 1)
return fig
def plotWReturn2(self):
fig = plt.plot(self.y,self.x,'-x',label='randWzw')
fig = plt.title('Plot With Return2')
plt.legend(numpoints = 3)
return fig
if __name__=='__main__':
f = myClass1()
p = plt.figure()
p1 = p.add_subplot(122)
p1 = f.plotWReturn1()
p1 = f.plotWReturn2()
print 'method with return: %s: ' % type(p1)
p2 = p.add_subplot(121)
p2 = f.plotNReturn1()
p2 = f.plotNReturn2()
print 'method without return: %s: ' % type(p2)
plt.show()
我注意到的唯一区别是输出的类型,但我不知道它在实践中意味着什么。
method with return: <class 'matplotlib.text.Text'>:
method without return: <type 'NoneType'>:
它只是关于“pythonic”练习还是有任何实用的任何风格?
答案 0 :(得分:2)
返回值只会对调用者产生直接影响,在本例中为__main__
块。如果您不需要重用函数计算的某些值,在您分配给p1或p2的情况下,返回对行为没有任何影响。
此外,还有一系列作业,如
p1 = call1()
p1 = call2()
p1 = call3()
是错误代码样式的指标,因为只有分配给p1的最后一个值才会在它们之后可用。
无论如何,我认为你想要绘制子图,而不是主图,如下:
import matplotlib.pyplot as plt
import numpy as np
class myClass1(object):
def __init__(self):
self.x = np.random.random(100)
self.y = np.random.random(100)
def plotNReturn1(self, subplot):
subplot.plot(self.x,self.y,'-*',label='randNxy')
subplot.set_title('Plot No Return1')
subplot.legend(numpoints = 1)
def plotNReturn2(self, subplot):
subplot.plot(self.y,self.x,'-x',label='randNzw')
subplot.set_title('Plot No Return2')
subplot.legend(numpoints = 2)
if __name__=='__main__':
f = myClass1()
p = plt.figure()
p1 = p.add_subplot(122)
f.plotNReturn2(p1)
p2 = p.add_subplot(121)
f.plotNReturn2(p2)
plt.show()
这里,子图被传递给每个函数,因此应该在其上绘制数据,而不是替换之前绘制的内容。