calling class/static method from class variable in python

后端 未结 4 2038
遥遥无期
遥遥无期 2020-12-19 03:38

I\'m trying to make a ImageLoader class handle the loading and processing of image resources like this:

class ImageLoader:
    TileTable = __loadTileTable(\'         


        
4条回答
  •  梦毁少年i
    2020-12-19 04:03

    In Python, the code in the class block is first executed, then the resultant namespace is passed to the class initializer. The code you wrote could have also been written as:

    TileTable = _loadTileTable(arg1, arg2)
    @staticmethod
    def _loadTileTable(arg1, arg2):
        pass # blah blah
    ImageLoader = type('ImageLoader', (), {'TileTable': TileTable, '_loadTileTable': _loadTileTable})
    del TileTable
    del _loadTileTable
    

    As you can see, the call of _loadTileTable appears before the definition of it. In your example, within the class definition, the call to _loadTileTable must come after the definition of _loadTileTable.

    One possible fix is to simply re-arrange the class definition.

    class ImageLoader:
        def _loadTileTable(arg1, arg2):
            pass # blah, blah
    
        TileTable = _loadTileTable('image path', other_var)
    

    Note that I removed the 'staticmethod', because at the point where _loadTileTable is called, it's being called as a function and not a method. If you really want it to be available after class initialization, you can define it as a static method after the fact.

    class ImageLoader:
        def _loadTileTable(arg1, arg2):
            pass # blah, blah
    
        TileTable = _loadTileTable('image path', other_var)
    
        _loadTileTable = staticmethod(_loadTileTable)
    

提交回复
热议问题