[英]importing a class from another python file issue
Hi I want to import a class from another file in python, everything works however the class I want to import receives a command line argument. 嗨,我想从python中的另一个文件导入一个类,一切正常,但是我要导入的类收到一个命令行参数。 After I import (which is successful) how would I supply that command line argument in the class? 导入(成功后)后,如何在类中提供该命令行参数? (side:note is this a superclass or something? idk what that means) (侧:注意,这是超类还是什么?idk是什么意思)
#class I'm importing
class trend:
def __init__(self):
self.user_name = sys.argv[1] #receives commandline argument
_______________________________________________________________
#class I want to use it in
class game:
def __init__(self):
self.twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
def do_something(self):
import filenameforthetrendclass as TC
game = TC.trend() #how do I bring in the commandline argument in here?
It's a bad idea to use sys.argv
anywhere but at the top-level ( main
, if you have one). 在顶级以外的任何地方( main
,如果有的话)都使用sys.argv
是个坏主意。 That's something you should pass in. 那是你应该传递的东西。
First, re-write Trend
to take user_name
as a parameter to its constructor. 首先,重新编写Trend
以将user_name
作为其构造函数的参数。
Quick example with just Trend
: 简单的Trend
示例:
class Trend(object):
def __init__(self, user_name):
self.user_name = user_name
trend = Trend(sys.argv[1])
Now integrating the whole concept: 现在整合整个概念:
import sys
from filenameforthetrendclass import Trend
class Game(object):
def __init__(self):
self.twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
def do_something(self, user_name):
a_trend = Trend(user_name) # was originally 'game = '
def main():
game = Game()
game.do_something(sys.argv[1])
Notes: 笔记:
game
and then using game
as a local variable somewhere. 我绝对没有一个名为game
的类,然后在某个地方使用game
作为局部变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.