【问题标题】:Importing variable from a different Python file containing self从包含 self 的不同 Python 文件导入变量
【发布时间】:2020-06-03 11:12:34
【问题描述】:

我有两个 Python 文件。一个调用另一个,我想将变量文档中的值放入不同 Python 文件的不同函数中。

a.py

class A:
def abc(object):
    self.document= 20

b.py

import a
def xyz():
    print(a.document)  // I need the value from document but there is an error.
    print(a.A.document)// I need the value from document which is 20 but it also gives me the error.

但是,这给了我错误:

no-member: Method

我怎样才能做到这一点?

【问题讨论】:

  • 请说明你想做什么。 a 没有变量 document。类a.A 的任何instance 都有这样的属性document.document 是否应该对所有实例都相同? xyz 是否应该在 a.A 的特定实例上工作?

标签: python python-3.x python-2.7 class


【解决方案1】:

在您的问题中看不到类初始化。

a.py:

class A:
    def __init__(self):
        self.document = 20

b.py:

from a import A

my_A = A()

print(f"{my_A.document=}")

【讨论】:

  • def __init__(self): 已经声明了,然后还有另一个函数,如果这样可以吗?
  • 您必须调用 __init__ 才能设置属性。
猜你喜欢
  • 1970-01-01
  • 2021-12-28
  • 1970-01-01
  • 2017-11-18
  • 2021-06-22
  • 2020-03-29
  • 2019-10-24
  • 2020-12-22
  • 1970-01-01
相关资源
最近更新 更多