Home > Back-end >  How to use function variable of one class to another class in Python
How to use function variable of one class to another class in Python

Time:04-15

How to access or use variable of one class in another class without creating their child class

Here is Code sample.

class A:
    def testA():
     self.a = "class A"

class B:
    def testB():
     **"Here I want to access self.a of class A"**
      

CodePudding user response:

You need an instance of A to access its variables.

class A:
    def testA(self):
        self.a = "class A"

class B:
    def __init__(self, a):
        self.a = a
    def testB(self):
        print(self.a.a)  # access the 'a' attribute of the local A class instance named 'a'

a = A()
a.testA()
b = B(a)  # <-- here
b.testB()

without creating their child class

You are not using inheritance, so there is no "child class"

  • Related