Referring to class methods in class attributes

Stephen Hansen apt.shansen at gmail.com
Wed Feb 17 18:59:11 CET 2010


On Wed, Feb 17, 2010 at 9:38 AM, mk <mrkafk at gmail.com> wrote:

> It works. But if I'd like to def print_internal_date in PYFileInfo body
> like so:
>
> class PYFileInfo(FileInfo):
>    'python file properties'
>
>    def print_internal_date(self, 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': PYFileInfo.print_internal_date
>            }
>

You don't have to (and can't) refer to the class within the body. Class
statements are sort of... odd. They are code which is directly executed, and
the results are then passed into a metaclass/type/whatever and a class
object is created. While within the class body, the class doesn't exist yet.

But you don't need it to.

Just do:

   'internal_date': print_internal_date

The 'def' is in the same local scope as 'tagdata' is.

--S
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20100217/c342ae6c/attachment.html>


More information about the Python-list mailing list