Using a method as callback for FileSelector?

Hi,
I want to call FileSelector inside a class with a member of this class as a callback and I get bad results, first try:


class ScnExporter:
    def my_function(self, filename):
        print 'The selected file was:', filename
 
    def chooseFile(self):
         Window.FileSelector(self.my_function, 'SAVE FILE')

scnExporter = ScnExporter()
scnExporter.chooseFile()

I get a:

AttributeError:
expected a callback function (and optionally one or two strings) as argument(s)

And now the same thing with a lambda function:


def chooseFile(self):
        Window.FileSelector(lambda filename, self=self: self.my_function(filename), 'SAVE FILE')

No errors, when I execute the script I see the dialog box but Blender segfault when I press “Save” :smiley: (It’s really the complete code).
Do you know how to make it works(at least case 1)?

I was doing the same thing last night, and I could only get it to work if I made the callback method a static class method, like:


class Exporter:
  def fileSelected(filename):
     # do something with filename
     pass
  fileSelected = staticmethod(fileSelected)

...

Window.FileSelector(Exporter.fileSelected, 'SAVE FILE')

This is to be expected. In the original post, the my_function() method is an instance method. To call my_function(), it needs to be bound to an object of type scnExporter like this: my_scnExporter.my_function().

Passing self.my_function as a parameter is not the same thing. The difference between instance methods and static ( or class ) methods is an important distinction in object oriented programming.

Is there an ‘object oriented’ reason why chatbox shouldn’t use an instance method for the callback, if python allowed it ?

Besides the fact that it doesn’t work, you mean?

If I understand the question, you are asking if there is some stylistic or conventional reason not to use an instance method. It is not a question of style, but rather the difference between an instance method and a static ( or class ) method.

A static method can be called without reference to a particular object. To call an instance method, you MUST have an object of the class type. It is possible to arrange for this inside a callback function but the instance object is usually a parameter

If I have misunderstood your question, please feel free to clarify. I am tempted to launch a long explanation of what an instance method actually is, but I don’t want to bore you with things you may already understand.

[/quote]

I meant in an imaginary world, where Blender’s Python API allowed chatbox to reference an instance method for this purpose, would it be wrong ? Because I couldn’t see how

The difference between instance methods and static ( or class ) methods is an important distinction in object oriented programming.

is one which in itself innevitably leads to the practical restriction this thread is concerned with.