如何从另一个函数和另一个类导入变量?

时间:2015-02-22 16:43:05

标签: python

我正在尝试,但它无法正常工作。我有以下代码行:

class Run:
    def Method(self, choice):
        print "%sZip        :\t%s%s\n".decode('utf-8') % (Basic_Green, White, choice.start().LoadJson['zip'])

这是变量,并且在另一个类中,还有另一个函数:

class Host_Method:
    def start(self):
        My_API =    requests.get("http://ip-api.com/json/%s" % socket.gethostbyname(sys.argv[2]))
        LoadJson =  json.loads(My_API.content)

错误:

Traceback (most recent call last):
  File "InfoIP.py", line 78, in <module>
    elif sys.argv[1]    ==  "-h": Run().Method(Host_Method())
  File "/Pentest/InfoIP2/Libraries/InfoIP_Functions.py", line 159, in Method
    print "%sZip        :\t%s%s\n".decode('utf-8') % (Basic_Green, White, choice.LoadJson['zip'])
AttributeError: Host_Method instance has no attribute 'LoadJson'

1 个答案:

答案 0 :(得分:0)

您可能希望将它们存储在实例变量(self....)中。你可能希望你的开始是一个__init__方法。您的更正课程可能如下所示:

class HostMethod:
    def start(self):
        self.my_API = requests.get("http://ip-api.com/json/{0}".format(socket.gethostbyname(sys.argv[2])))
        self.load_json = json.loads(self.my_API.content)

然后,你可以这样做:

class Run:
    def Method(self, choice):
        print "{0}Zip        :\t{1}{2}\n".decode('utf-8').format(Basic_Green, White, choice.load_json['zip'])

a = Run()
a.method(HostMethod())

另见: