I would like to pass a class as an argument to another class and then call methods of the class that I passed but I am getting different errors. I started with this but my code keeps giving me errors.
Consider the following situation:
class A:
A_class_var = "I am an A class variable"
def __init__(self):
self.A_inst_var = "I am an A instance variable"
def GetClassVar(self):
return A_class_var
def GetInstVar(self):
return self.A_inst_var
class B:
def __init__(self, cls):
print cls.GetClassVar()
print cls.GetInstVar()
1) When I call b = B(A) I get an "unbound method GetClassVar() must be called with A instance as first argument (got nothing instead)." So I figure that GetClassVar() and GetInstVar() expected an A instance and tried adding cls to the arguments of the two calls in B's __init__. Same error.
2) When I tried calling b = B(A()) I get the error "global name A_class_var" is not defined.
3) When I tried calling a = A() followed by b = B(a) I got the same error as in #2.
4) When I tried to do the suggestion in the SO answer I linked above, namely change the definition of B to:
class B:
def __init__(self, cls):
self.my_friend = cls
def GetFriendsVariables(self):
print my_friend.GetClassVar()
print my_friend.GetInstVar()
and then call b = B(A) followed by b.GetFriendsVariables() (also following that SO I linked) I get the error "global name my_friend is not defined" in GetFriendsVariables.
I'd really like to understand how to properly pass classes as arguments so that I can access variables and methods of those classes and would love to understand why my various attempts above don't work (and yet the SO link I sent does?)
Thanks very much!
a = A(), then passb=B(a)That isais instance of Aself.A_class_varA_class_varas a class variable (when I make the changeself.A_class_varinsideA::GetClassVar()only). Thanks, but would really like to understand what is going on under the hood here. I want to learn more than I want it to run. :)