简体   繁体   中英

Passing 'self' as an argument in a function call?

In my gui application (PyQt 5) I have a couple of code pieces appearing repeatedly in different modules. This is an example:

save_file = QFileDialog.getSaveFileName(
                                    self,
                                    "Save",
                                    directory="path/to/filename"
                                )
save_path = save_file[0]

I thought about writing a function for that like this:

def save_file(obj, title, preset):
    save_file = QFileDialog.getSaveFileName(obj, title, preset)
    save_path = save_file[0]
    return save_path

And whenever I need it ( in some class ) I would call it in this way:

save_file(self, "Save testfile", os.path.join(file_path, file_name))

In this case I would have to pass self as an argument to my function. Is this ok? I know I can pass an instance of a class as an argument. But is it a good idea passing self directly when calling the function within a method? I couldn't find much about that on the internet.

That is fine, though the convention is to use the following format:

self.save_file("Save testfile", "path/to/filename")

Though the save_file should probably be within a class and its method definition look like:

def save_file(self, title, preset):
    ...

self is typically used to refer to this object. The one in whose method you are currently. You have not given enough context for a complete answer, but you should read up on python classes, and the use of class methods. Here's a tutorial .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM