calling class/static method from class variable in python

后端 未结 4 2046
遥遥无期
遥遥无期 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条回答
  •  感动是毒
    2020-12-19 03:57

    Is there a design reason you're using a static method? If so, because you're not overloading the class initialization, you'll need to declare the variable after the method definition.

    But, if you do this, you'lll get a new error:

    NameError: name 'arg1' is not defined
    

    The reason for this is because you're executing the method within the class before the class is even instantiated, therefore you never have a chance to pass the arguments to the method.

    So, the proper way to do this is to overload the __init__() method so that assignment to TileTable only happens when the class is constructed:

    class ImageLoader(object):
        def __init__(self, arg1, arg2):
            self.TileTable = self._loadTileTable(arg1, arg2)
    
        @staticmethod
        def _loadTileTable(arg1, arg2):
            print arg1, arg2
    

    This gives you the ability to call ImageLoader._loadTileTable() without having an instance, but then it also allows you to create the TileTable instance variable upon creating an instance.

    Using a Class method
    In response to my comment about the possible need for a classmethod, here is an example that covers this:

    class ImageLoader:
        @classmethod
        def _loadTileTable(cls, arg1, arg2):
            return arg1, arg2
    
    # We're creating the class variable outside of the class definition. If you're doing 
    # this in a module, no one will ever notice.
    ImageLoader.TileTable = ImageLoader._loadTileTable('foo', 'bar')
    

    There might be a better way to do this, I don't know. But I do think that this covers what you are looking for:

    >>> i = ImageLoader()
    >>> i
    <__main__.ImageLoader instance at 0x100488f80>
    >>> ImageLoader.TileTable
    ('foo', 'bar')
    >>> i.TileTable
    ('foo', 'bar')
    

    There you have an instance i that has access to the class variable, but ImageLoader.TileTable is still available from the class object without the need for an instance.

提交回复
热议问题