Reputation: 92
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
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
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