class - How to use variable in different classes in Python? -


here code:

class projectapp(tk.tk):        def __init__(self, *args, **kwargs):         tk.tk.__init__(self, *args, **kwargs)          self.filepaths = []  class startpage(tk.frame):      def __init__(self, parent, controller, *args, **kwargs):         tk.frame.__init__(self, parent, *args, **kwargs)         self.controller = controller         self.parent = parent      def get_file(self):          filepath = askopenfilename()          if filepath:             print(projectapp.filepaths)             self.parent.filepaths.append(filepath) 

i trying use filepath in class got error below.

attributeerror: type object 'projectapp' has no attribute 'filepaths' 

can tell me mistake?

this depend of want. there 2 kind of attribute object: class attribute , instance attribute.

class attribute

the class attribute same object each instance of class.

class myclass:     class_attribute = [] 

here myclass.class_attribute define class , can use it. if create instances of myclass, each instance have access same class_attribute.

instance attribute

the instance attribute usable when instance created, , unique each instance of class. can use them on instance. there defined in method __init__.

class myclass:     def __init__(self)         self.instance-attribute = [] 

in case filepaths define instance attribute. can change class this, print(projectapp.filepaths) work.

class projectapp(tk.tk):       filepaths = []      def __init__(self, *args, **kwargs):         tk.tk.__init__(self, *args, **kwargs) 

if need more explaination, advice read this part of python documentation


Comments