Calling class attribute without creating an instance to that class
I would like to initialize a class, then call an attribute which was set during the initialization, but without creati开发者_如何转开发ng another instance. As a test example:
class t1:
def __init__(self, skipInit=False):
if not skipInit:
print 'Initialized'
self.var = 123456
else:
print 'Not Initialized'
def returnVar(self):
return self.var
class t2:
def getVar(self):
print t1.returnVar(t1)
I want to initialize t1 with t1()
, and later on, access to var from t2, with t2.getVar(t2)
or some other way from within t2. Obviously the above code is not working, and I have a hard time understanding why.
In actuality the classes are in a wxPython program. There is a Frame->Notebook->Panel->MenuBar hierarchy, all in separate files. I set a number of variables during the Panel initialization, and try to access these from one of the menu items on the GUI. At that point panel will already be initialized and shown, which why I added the skipInit switch. Any ideas on how to do this?
There's nothing called t1.var
, so of course you can't access it. var
is an attribute of a t1
instance; it doesn't exist on the class. Since you can have any number of instances of t1
, there's no way for an instance method of t2
to know which t1
instance it should look for the attribute var
in without you telling it. You can do this when you instantiate t2
.
# t1 class is the same as yours
class t2:
def __init__(self, t1):
self.t1 = t1
def getVar(self):
print self.t1.returnVar(t1)
obj1 = t1()
obj2 = t2(obj1) # give the t2 instance the t1 instance
print obj2.getVar()
If I understand the problem correctly, then you just need to pass your instance of t1 to an instance of t2.
class t2:
def getVar(self, t1):
print t1.returnVar(t1)
t1_instance = t1()
t2_instance = t2()
t2.getVar(t1_instance)
Maybe this is what you want?
class T1(object): # Subclassing object makes a new-style class
def __init__(self):
self.var = 123456
t1 = T1()
# t1 is now an instance of T1. This calls __init__ to set it up.
print t1.var # 123456
精彩评论