İzzet KILIÇ İzzet KILIÇ - 1 year ago 46
Python Question

How to use variable in different classes in Python?

Here is my 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:

I am trying to use filepath in another class but I got the error below.

AttributeError: type object 'ProjectApp' has no attribute 'filepaths'

Can you tell me where is the mistake?

Answer Source

This will depend of what you want. There is two kind of attribute for object: The class attribute and the instance attribute.

Class attribute

The class attribute is the same object for each instance of the class.

class MyClass:
    class_attribute = []

Here MyClass.class_attribute is already define for the class and you can use it. If you create instances of MyClass, each instance would have access to the same class_attribute.

Instance Attribute

The instance attribute is only usable when the instance is created, and is unique for each instance of the class. You can use them only on an instance. There are defined in the method __init__.

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

In your case filepaths is define as an instance attribute. you can change your class for this, your print(ProjectApp.filepaths) will work.

class ProjectApp(tk.Tk):  
    filepaths = []

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

If you need more explaination, i advice you to read this part of the python documentation