Pass instance as function argument
I wrote a nice little app that gets Yahoo weather info and posts it to Twitter. It worked flawlessly and now I want to rearrange the code into differently named files so it makes more sense. And that's when I hit some issues.
Previously, I had a Class
in libtweather.py
. It was my account
. It allowed me to do accountName.parseFeed()
and I'd get as output the parsed Yahoo weather. (__ini__
took the weather URL, twitter username and password as args)
This was accessed from my main script which created instances of the Class
like this:
exec '%s = lw.twitterWeather("%s", "%s", "%s")' % (item[0], item[1], item[2], item[3])
It kept a list of all account names in a list which was passed as argument to the other functions.
Another function getWeather
got weather by doing:
def getWeather(accountList): #account names passed as a list of strings
for item in accountList:
print item, ': ',
item = eval(item)
print item.parseFeed(), '\n
I've decided now to move the getWeather
function to the same file as the Class
but the line item = eval(item)
's giving me problems because there are no instances created in that file. All of them are in the main script.
Now my question: Is there some way I could give those instances as arguments to the function? Or must I put the function into the Class
? Even if I did that, I'd still need to do the item.parseFeed()
for multiple items in the list so I'd still need the item = eval(item)
, no?
Thanks in advance. My app's a tad bit to post here in entirety, but I'll post more code if needed to understand better.
Updat开发者_运维知识库e: I ended up running my libtweather.py
to create instances when it's imported so that the functions inside it can access them (added the instance generating code at the bottom of the script). I'm sure there's a better way but it works for me currently and I'm OK with that.
You should be using an explicit dict for storing these items. eval
, exec
, globals
, locals
, and vars
are all horribly silly ways to do this poorly. Remember from the Zen of Python: "explicit is better than implicit."
feeds = {}
for item in whatever:
feeds[item[0]] = lw.twitterWeather(*item[1:])
def getWeather(feeds, accountList):
for item in accountList:
print '%s: %s' % (item, feeds[item].parseFeed())
精彩评论