Ex43 help: Passing variable between classes

Hello, I’m trying to add an HP counter that increases/decreases depending on the choices being made in the game. I’m struggling though passing that value between classes. The following works to pass a variable from Parent to Child classes:

class Parent(object):
var1 = 1

class Child(Parent):
def fun(self):
var2 = Parent.var1 + 1
return var2

p = Parent()
a = p.var1
print(f’{a}’)

c = Child()
b = c.fun()
print(f’{b}’)

However, when you add a third class it gives an error:

class Grandkid(Child):
def fun2(self):
var3=Child.var2+1
return self.var3

c = Grandkid()
d = c.fun2()
print(f’{d}’)

Any help would be greatly appreciated.

I’ll give you a quick hint, don’t have much time: Read up on

  • class attributes
  • instance attributes
  • local variables

If you don’t find the answer, ask again and I’ll explain what’s going on. :slight_smile:

Hmm trying that helped me identify the instance attributes, but I’m struggling with it. Any further hints would be helpful!

Which of the three types of variables is var2 and how are you trying to access it in Grandkid.fun?

By the way, you don’t need an f-string to print a variable. You can simply do print(var).

I believe var1 is a class variable, but var2 is an instance variable - but I’m trying to access both as a class variable?

Close. var2 is actually a local variable that exists only during the execution of Child.fun.

You could make it an instance attribute of c that persists as long as c exists by defining it on self:

self.var2 = Parent.var1 + 1

Then you could access it as c.var2.

If you wanted it to be a class attribute you’d have to define it on Child:

Child.var2 = Parent.var1 + 1

Then you could later access it as Child.var2.

1 Like

Ah ok I understand now - thank you so much for your help!