1

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:
            print(ProjectApp.filepaths)
            self.parent.filepaths.append(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?

1
  • 1
    filepaths is bound to an instance, not the class. ProjectApp().filepaths Commented Aug 1, 2016 at 11:47

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

2

You need to create an instance of the ProjectApp

myProjectApp = ProjectApp() 

Then you will be able to call the attribute filepaths

print(myProjectApp.filepaths)

1 Comment

But ProjectApp is my main app if I create an instance of it then a new frame opens.
1

filepaths is an instance attribute. I.e. filepath only exists after ProjectApp has been instantiated via the constructor call (= init ).

When instantiating StartPage, you should do it like that:

app = ProjectApp() # her you create the ProjectApp instance with filepaths
start_page = StartPage(app, ....)

and remove print(ProjectApp.filepaths), since this will throw an error.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.