首页 > 解决方案 > 在导入的模块中无法访问 Python 类实例变量

问题描述

从单独文件中的方法调用实例变量时,我无法访问它们。这是一个虚拟脚本作为示例。

项目文件夹

#main.py
class Dummy_Error_Class:
  def __init__(self, error_presence):
    self.__error = error_presence

  def check_error(self):
    if self.__error == True:
      print('Error Present')
    else:
      print('No Error Present')

  from function_library.testfunction import flip_error

dummy_error = Dummy_Error_Class(False)

dummy_error.check_error()

dummy_error.flip_error()

dummy_error.check_error()

test_function.py 中引用/导入的模块是:

def flip_error(self):
    print(self.__dict__)
    
    error = self.__error
    if error == True:
        self.__error = False
    elif error == False:
        self.__error = True

当我运行脚本时, print(self. dict ) 给了我 {'_Dummy_Error_Class__error': False} 但随后会引发“AttributeError: 'Dummy_Error_Class' object has no attribute '__error'”

知道这里发生了什么吗?我很感激这里的任何帮助!

标签: pythonmethodsimportinstance-variables

解决方案


推荐阅读