gpt4 book ai didi

python - 绘图方法是否需要返回?

转载 作者:行者123 更新时间:2023-11-28 22:57:45 25 4
gpt4 key购买 nike

我有一个类,其中包含构建一些图的方法。我尝试在一张图上显示不同的图。图的属性(标题、图例...)总是被最后一个图覆盖。我预计如果我的方法中有 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”实践还是有任何实际使用任何风格的东西?

最佳答案

返回一个值只对调用者有直接影响,在本例中是你的 __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()

这里,subplot 被传递给每个函数,因此应该在其上绘制数据,而不是替换您之前绘制的内容。

关于python - 绘图方法是否需要返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14487363/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com