I have checked many questions replied here, but can't access an instance variable from another class(I have tried this as example)
#in file: view.py
class treeview():
def __init__(self):
....(no mention of row_num)
def viewer(self, booklist, act=-1):
row_num = len(treeview().full_list)
print(row_num) # prints the correct value, which is > 0
return row_num
#in main file
class Window(Gtk.ApplicationWindow):
def __init__(self, application, giofile=None):
self.TreeView = view.treeview()
def extract_data_from_cr(self, select_button):
print(self.TreeView.row_num)
Gives error:
AttributeError: 'treeview' object has no attribute 'row_num'
If I try to add row_num
inside treeview() as:
class treeview():
def __init__(self):
self.row_num = 0
def viewer(self, booklist, act=-1):
self.row_num = len(treeview().full_list)
print(self.row_num)
# return row_num
then, print(self.TreeView.row_num)
in main
always yields 0
.
I cant find whats going wrong here.Kindly help.
After Mitch's comment if I define row_num without calling treeview() again as:
class treeview():
def __init__(self):
self.row_num = 0
def viewer(self, booklist, act=-1):
self.row_num = len(self.bookstore)
print(type(self.bookstore)) # <class 'gi.overrides.Gtk.ListStore'>
print(self.row_num) # 5 (expected for a particular case)
Now, when calling the def extract_data_from_cr
, I am expecting this number:
def extract_data_from_cr(self, select_button):
print(self.TreeView.row_num) #is giving 0
A MCVE
$cat mcve.py
class classA():
def __init__(self):
self.row_num = 0
print("HiA")
def define(self):
la = ["A", "B", "C"]
self.row_num = len(la)
print(self.row_num) #prints 3 when get called from mcve2
return(self.row_num)
classA().define()
and
$cat mcve2.py
#!/usr/bin/python
import mcve
class classB():
def get_val(self):
self.MCVE = mcve.classA()
print("Hi2")
print(self.MCVE.row_num) #prints 0
classB().get_val()
Result:
python3 mcve2.py
HiA
3
HiA
Hi2
0
I know. if I call ClassA.define()
explicitely from ClassB.get_val()
, I will get the desired value. But I am looking for transfaring the value it got (Result: line 2
)