【问题标题】:python 2.7 Use inside one function a method of a class, when class instance is in another functionpython 2.7在一个函数中使用一个类的方法,当类实例在另一个函数中时
【发布时间】:2017-07-21 11:22:58
【问题描述】:

这是一个代码示例:

module1.py 在 main 中导入。 在 modul1.py 中有一个 init() 函数,它从之前导入的库中创建类,然后,其他函数使用该类的该实例以及该类的方法。

ERROR: global name name1  not defined

module1.py:

from lib import class1, classs2

def init():
    name1.class1()


def function():
    name1.class1method1()

ma​​in.py:

import module1
init()

function()

我需要帮助,谢谢

【问题讨论】:

  • 您只需调用一个不存在的名称(变量、模块或其他)name1

标签: python-2.7 class methods instance


【解决方案1】:

我认为您可能对从类定义创建对象和访问类的方法感到困惑。您收到未定义错误,因为您尚未定义name1

通过以下调整,您的代码将可以工作:

module1.py:

from lib import class1, classs2

def Init():
    global name1
    name1 = class1()


def function():
    name1.class1method1()

ma​​in.py:

import module1
module1.Init()

module1.function()

话虽这么说全局变量是个坏主意,所以上面的代码仅用于演示目的,不用于实际使用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-18
    • 2014-05-31
    • 1970-01-01
    • 2020-11-16
    • 2020-10-23
    相关资源
    最近更新 更多