Static method

Stefan Behnel stefan_ml at behnel.de
Thu Feb 18 12:32:51 CET 2010


mk, 18.02.2010 12:12:
> I'm trying to get print_internal_date become a static method AND to
> refer to it in a class attribute 'tagdata' dict.
> 
> class PYFileInfo(FileInfo):
>     'python file properties'
> 
>     @staticmethod
>     def print_internal_date(filename):
>         f = open(filename + 'c', "rb")
>         data = f.read(8)
>         mtime = struct.unpack("<i", data[4:])
>         return time.asctime(time.gmtime(mtime[0]))
> 
>     tagdata = {'compiled_fname': lambda x: x + 'c',
>                 'size': os.path.getsize,
>                 'internal_date': print_internal_date
>             }

You can 'unroll' the decorator like this:

class PYFileInfo(FileInfo):
    def print_internal_date(filename):
        f = open(filename + 'c', "rb")
        data = f.read(8)
        mtime = struct.unpack("<i", data[4:])
        return time.asctime(time.gmtime(mtime[0]))

    tagdata = {'compiled_fname': lambda x: x + 'c',
                'size': os.path.getsize,
                'internal_date': print_internal_date
            }

    print_internal_date = staticmethod(print_internal_date)

You can also define the function outside of the class and then assign it to
a class attribute, i.e.

def _print_internal_date(filename):
    f = open(filename + 'c', "rb")
    data = f.read(8)
    mtime = struct.unpack("<i", data[4:])
    return time.asctime(time.gmtime(mtime[0]))

class PYFileInfo(FileInfo):
    print_internal_date = _print_internal_date

    tagdata = {'compiled_fname': lambda x: x + 'c',
                'size': os.path.getsize,
                'internal_date': _print_internal_date
            }

Quite likely, there are other ways to achieve what you want more cleanly,
but without more background on your intended use case, it's hard to give
better advice.

Stefan



More information about the Python-list mailing list