【问题标题】:how should i access a class variable from another class in python?我应该如何从 python 中的另一个类访问一个类变量?
【发布时间】:2020-10-18 00:33:06
【问题描述】:

我在 Stackoverflow 上检查了很多网站以及几乎所有与此相关的问题。我找不到这个问题的解决方案。它对于一个项目非常重要。请帮忙。我想在 B 类的函数 email(self) 中使用 A 类中的变量 self.email。我尝试了几件事,但它不起作用。继承不起作用,因为它是一个 kivy-python 代码并且它已经继承了像 GridLayout() 这样的类。

Class A:
    def __init__(self):
        ---some code---
    def email_id(self):
        self.email = x

Class B:
    def __init__(self):
        print(A().email)

【问题讨论】:

  • 那么,使用A().email有什么问题?
  • 它不工作
  • 我可以在类之外声明一个空变量,然后将值存储在其中吗?我试过了,但是当我在另一个类中调用变量时,变化是不可见的
  • 试试:tmp_a = A(); tmp_a.email_id(); print(tmp_a.email)
  • email 在初始化之前将无法访问 - 您在 email_id 中执行此操作,因此除非您在 A() 上调用 email_id,否则它将不存在

标签: python class global-variables class-variables


【解决方案1】:

我认为您可能正在寻找的是property decorators

Class A: 
    def __init__(self): 
        ---some code--- 
    @property
    def email(self): 
        return (some code to show the email)

【讨论】:

    【解决方案2】:

    A 类的字段email 是在调用email_id() 时创建的。 因此,在执行print(A().email) 时,该字段仍未设置。

    你可以先设置

    Class B:
        def __init__(self):
            a = A()
            a.email_id("email")
            print(a.email)
    

    【讨论】:

      猜你喜欢
      • 2013-11-28
      • 1970-01-01
      • 2017-07-14
      • 2023-04-07
      • 2020-11-24
      • 1970-01-01
      • 1970-01-01
      • 2011-10-22
      • 1970-01-01
      相关资源
      最近更新 更多