Referring to class methods in class attributes

M

mk

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top