开发者

function arguments in python

I'm trying to wrap my head around the way positional and keyword arguments work in python, and, it seems, I'm failing rather miserably.

Given a function with a call signature matplotlib.pyplot.plot(*args,**kwargs), it can be called as

import matplotlib.pyplot as plt

x=[1,2,3]
y=[5,6,7]
plt.plot(x,y,'ro-')
plt.show()

Now, I'm trying to wrap it into something which I can call as mplot(x,y,'ro-',...) where ... are whatever arguments the original function was ready to accept. The following fails miserably, but I can't really figu开发者_JAVA技巧re how to fix it:

def mplot(x,y,fmt,*args,**kwargs):
   return plt.plot(x,y,fmt,*args,**kwargs)

mplot(x,y,'ro-')

Any pointers to a way out would be very much appreciated.


You need it this way:

def mplot(x,y,fmt,*args,**kwargs):
   #do stuff with x, y and fmt
   return plt.plot(*args,**kwargs)

I'm assuming that your intention is to consume the x, y and fmt in your mplot routine and then pass the remaining parameters to plt.plot.


I don't believe that this is actually what you want (I can see that plt.plot wants to receive x, y and fmt and so they should not be consumed). I had deleted this answer but since your posted code apparently works, I'll leave this visible for a little while and see if it provokes the real question to be revealed!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜