【问题标题】:Accessing an instance's methond from a function in another module从另一个模块中的函数访问实例方法
【发布时间】:2020-07-16 15:05:36
【问题描述】:

菜鸟问题。

我有以下简单的代码:

class Test():

    def __init__(self):
        self.foo = "foo"

    def bar(self):
        self.foo = "bar"

def action():
    a = input("Anything>")
    spam.bar()
    print(spam.foo)

spam = Test()

action()

它按预期显示“条形图”。

当我把它分成两个文件时: test_main.py:

from test_module import action

class Test():

    def __init__(self):
        self.foo = "foo"

    def bar(self):
        self.foo = "bar"


spam = Test()

action()

还有 test_module.py:

def action():
    a = input("Anything>")
    spam.bar()
    print(spam.foo)

函数 action() 无法访问对象“垃圾邮件”:

  File "test_main.py", line 14, in <module>
    action()
  File "/home/krzysztof/Documents/dev/Python Crash Course/12/test_module.py", line 3, in action
    spam.bar()
NameError: name 'spam is not defined'

我知道这种访问是可能的,但我找不到有关如何进行访问的信息。我错过了什么?

【问题讨论】:

    标签: python class import module instance


    【解决方案1】:

    您之前可以访问spam,因为它是同一文件中的全局变量。您不能直接从其他文件访问全局变量。

    这样做的正确方法是更改​​action() 以将垃圾邮件作为参数:

    def action(spam):
        a = input("Anything>")
        spam.bar()
        print(spam.foo)
    

    然后改用action(spam) 调用它。

    【讨论】:

      【解决方案2】:

      您可以将spam 类的实例作为参数传递给您的操作函数。并更改函数的定义。

      test_main.py

      from test_module import action 
      class Test(): 
          def __init__(self): 
              self.foo = "foo" 
          def bar(self): 
              self.foo = "bar" 
      
      spam = Test() 
      action(spam)
      

      test_module.py

      def action(spam): 
          a = input("Anything>") 
          spam.bar() 
          print(spam.foo)
      

      【讨论】:

        【解决方案3】:

        当您导入测试模块文件时,该文件中的整个代码会在导入之前运行。所以 test_module 文件中不存在 spam 变量。 你应该在 action 函数中使用 spam 作为参数。

        【讨论】:

          【解决方案4】:

          你可以使用

          from test_main import bar
          

          你可以使用类似这种格式的东西

          from FOLDER_NAME import FILENAME
          from FILENAME import CLASS_NAME FUNCTION_NAME
          

          【讨论】:

          • 请解释这是如何解决问题的。如果这不是错误,那肯定会导致循环导入。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-05-15
          • 2020-03-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-08-04
          • 2012-12-18
          相关资源
          最近更新 更多