Referring to class methods in class attributes

mk mrkafk at gmail.com
Wed Feb 17 12:38:14 EST 2010


Hello everyone,

OK so I have this:

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):
     'python file properties'

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

     def __init__(self, fname=None):
         FileInfo.__init__(self,fname)

     def __setitem__(self, key, value):
         FileInfo.__setitem__(self, key, value)
         if key == 'name' and value:
             print value
             self.__get_props(value)

     def __get_props(self, value):
         py_compile.compile(value)
         for tag, fun in PYFileInfo.tagdata.items():
             self[tag] = fun(value)
...


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
             }

I get:

c:/Python26/pythonw.exe -u  "C:/mp3i/finfo2.py"
Traceback (most recent call last):
   File "C:/mp3i/finfo2.py", line 53, in <module>
     class PYFileInfo(FileInfo):
   File "C:/mp3i/finfo2.py", line 64, in PYFileInfo
     'internal_date': PYFileInfo.print_internal_date
NameError: name 'PYFileInfo' is not defined


Hmm do I get that class data attributes are defined before class is 
defined?!

Why I would like to do it this way:

1. keeping all the stuff specific to PYFileInfo where it belongs, in a 
class: the print_internal_method does nothing but read timestamp from a 
.pyc file, so it's not a generic function.

2. I guess I could define tagdata in __init__ and be done with it: 
however, it's an instance attribute then and not class attribute: a few 
bytes are wasted. Seriously, however, suppose tagdata or smth like this 
is really large? It would make sense to make it class attribute and not 
instance attribute. So I'm trying to work out if there's a way to do it.


Regards,
mk




More information about the Python-list mailing list