【问题标题】:Access variable of a class in another classAccess variable of a class in another class
【发布时间】:2022-12-27 22:34:03
【问题描述】:

How can I access the variables x and y defined inside funA in class A from class B?

class A(QWidget):
  def __init__(self):
    QWidget.__init__(self)

    self.y = 1
  def funA(self):
    self.x = 1
    self.y = 2
    return self.x, self.y


class B(QMainWindow):
  def __init__(self, name, low, high, step=10, a):
    QMainWindow.__init__(self)
    a = A.funA()
    print(a)

a = A()    
B(a)

Can someone help me with this?

【问题讨论】:

  • I see you have posted some code for us to see. Does it work? Do you get anything printed out? Are there any errors?
  • Are you looking for a.x and a.y?
  • Yes, I would like to access x and y from class B @mkrieger1
  • No, this code does not work correctly @quamrana

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


【解决方案1】:

funA is a non-static method (indicated by the self argument and the lack of classmethod decorator). You've called it on the class directly with no self, so your current code will indicate that funA has been given too few arguments.

Instead, create an instance of A and call it on that.

a = A()
a.funA()

Now funA tries to return some variables self.a and self.b that don't exist. Either remove those lines or change them to something that does.

def funA(self):
  self.x = 1
  self.y = 2
  return self.x, self.y # Or just remove this line entirely

Then, once you've called the method on an actual instance, you can get the instance variables off that instance.

print("x = ", a.x)
print("y = ", a.y)

【讨论】:

    【解决方案2】:

    1.using inheritance:

    class A:
        x = 10
    
    class B(A):
        def access_x(self):
            print(self.x)
    
    b = B()
    b.access_x()  # Output: 10
    

    【讨论】:

      猜你喜欢
      • 2015-10-18
      • 2022-12-01
      • 2022-12-01
      • 1970-01-01
      • 2019-09-29
      • 2016-06-23
      • 2022-12-02
      • 2022-12-01
      • 2022-05-09
      相关资源
      最近更新 更多