我有一个类,其中包含构建一些绘图的方法。我尝试在一张图上显示不同的图。图形的属性(标题、图例...)始终会被最后一个图覆盖。我预计,如果我的方法中有 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”实践还是有任何实用的风格可以使用?
最佳答案
返回值仅对调用者(在本例中为 __main__
block )产生直接影响。如果您不需要重用函数计算的某些值(在分配给 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()
这里,子图被传递给每个函数,因此应该在其上绘制数据,而不是替换之前绘制的内容。
关于python - 绘图方法需要返回吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14487363/