ATEK0
ATEK0

Reputation: 92

How can I pass a variable from one class to another in Python?

I'm creating a little stock management app and I want to access a variable from ClassA in ClassB

ClassA(Screen):
     def test1(self):
          self.username = "Tonny"

ClassB(Screen):
     def test2(self):
          print(ClassA.test1.username)

This code dont work, i already tried like this:

ClassA(Screen):
     def test1(self):
          self.username = "Tonny"
          return self.username

ClassB(ClassA,Screen):
     ClassA = ClassA()
     def test2(self):
          print(ClassA.test1())

The second piece of code should work, but I can't use it because of the screen manager, it stop working right when I put another argument in the class.

Does anyone know how can I do this?

Upvotes: 0

Views: 3386

Answers (2)

Oghli
Oghli

Reputation: 2340

You can do it by sending the instance of ClassA to ClassB in order for ClassB to access it:

class ClassA(object):
    def __init__(self):
        self.username = "Tonny"
        
class ClassB(ClassA):
    def __init__(self, class_a):
        self.username = class_a.username

    def getPassedName(self):
        return self.username

object1 = ClassA()
object2 = ClassB(object1)
username = object2.getPassedName()
print(username)

For more info check this question.

Upvotes: 1

user12479200
user12479200

Reputation:

self.x means a variable x just works inside the class definition. Try this: Define a class A(object), define x=1 before init()

class A(object):
    x = 1
    __init__(self)
    .....

You can address x like A.x.

Upvotes: 1

Related Questions