【问题标题】:Inside class, can i call other methods variable inside another method?在类中,我可以在另一个方法中调用其他方法变量吗?
【发布时间】:2022-01-19 06:24:10
【问题描述】:
class A:
    def __init__(self):
        self.a=10


        
    def bvalue(self):
        self.b=20
         
    def add1(self):
        c=self.a+self.b
        print(c)
        
a1=A()
a1.add1()

ouput
 AttributeError: 'A' object has no attribute 'b'

我在 init 方法中声明 a=10 并在另一个方法中声明 b=20,并使用第三种方法尝试添加 a+b。但为什么它给出错误? 我在这里犯了什么错误吗?

【问题讨论】:

标签: python class methods init


【解决方案1】:

你应该在调用 add1 之前先调用方法 bvalue

尝试:

a1=A()
a1.bvalue()
a1.add1()

【讨论】:

  • 是的,兄弟,现在可以使用了,非常感谢您的帮助
猜你喜欢
  • 2010-11-28
  • 1970-01-01
  • 1970-01-01
  • 2021-05-26
  • 2018-03-27
  • 2015-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多