Python-导入类模块时出现NameError

时间:2020-01-14 20:12:11

标签: python class import nameerror

运行脚本时出现以下错误:
NameError:名称'curr_period_2'未定义

我没有太多使用Classes,这是我第一次将它们放在单独的模块中。

我想做的就是使用change_object函数更改一个对象属性。

不要考虑代码的作用,因为这只是一个小测试。

非常感谢您的帮助。

MyClass.py

class MyPeriod:

def __init__(self, year, month):
    self._year = year
    self._month = month

@property
def year(self):
    return self._year


@year.setter
def year(self, year):
    self._year = year

MyMain.py

    from MyClass import MyPeriod

    def main():
        curr_period = MyPeriod(2028, 1)
        print(f'Object 1 is {curr_period.year}-{curr_period._month}')
        curr_period.year = curr_period.year + 1
        print(f'Object 1 +1  is {curr_period.year}-{curr_period._month}')

    def init_object():
        curr_period_2 = MyPeriod(2038, 1)
        print((f'Object 2 is {curr_period_2.year}-{curr_period_2._month}'))

    def change_object():
        curr_period_2.year = curr_period_2.year * 2
        print(f'Object " * 2' is {curr_period_2.year}-{curr_period_2._month})

    init_object()
    change_object()

    if __name__ == "__main__":
        main()

2 个答案:

答案 0 :(得分:0)

curr_period_2change_object中不存在,因为它是init_object函数的局部变量。您可以尝试将其作为参数传递给change_object函数:

def init_object():
    curr_period_2 = MyPeriod(2038, 1)
    print((f'Object 2 is {curr_period_2.year}-{curr_period_2._month}'))
    return curr_period_2

def change_object(current_period_2):
    curr_period_2.year = curr_period_2.year * 2
    print(f'Object " * 2' is {curr_period_2.year}-{curr_period_2._month})

然后:

period = init_object()
change_object(current_period_2=period)

或者尝试使用global变量

答案 1 :(得分:0)

main(),init_object()和change_object()是“独立/本地/独立”函数,因此内部的变量仅是本地的(不是全局的)。

解决这个问题的最好方法就是在这些函数内部将这些内部变量声明为Global。

请参阅:

from MyClass import MyPeriod

def main():
    # first of all declare curr_period as global
    global curr_period

    curr_period = MyPeriod(2028, 1)
    print(f'Object 1 is {curr_period.year}-{curr_period._month}')
    curr_period.year = curr_period.year + 1
    print(f'Object 1 +1  is {curr_period.year}-{curr_period._month}')

def init_object():
    #same here "Global" declaration
    global curr_period_2

    curr_period_2 = MyPeriod(2038, 1)
    print((f'Object 2 is {curr_period_2.year}-{curr_period_2._month}'))

def change_object():
    curr_period_2.year = curr_period_2.year * 2
    print(f'Object " * 2' is {curr_period_2.year}-{curr_period_2._month})

init_object()
change_object()

if __name__ == "__main__":
    main()