How to derive a class from md5?

J

Josef Wolf

Hello!

I'd like to create a class to calculate md5's of a file. So I thought, I'd
derive from the md5 class. I came up with following code:

#!/usr/bin/python

import md5

class md5file(md5):
def __init__(self, filename):
md5.__init__(self)
f=file(filename,"r")
for l in f:
self.update(l)
f.close()

print md5file("/etc/passwd").hexdigest()

But running this gives me the following error:

Traceback (most recent call last):
File "py/t.py", line 5, in ?
class md5file(md5):
TypeError: function takes at most 2 arguments (3 given)

dir(md5) shows that md5 don't have an __init__() method so I tried to use
its new(), with the same result. What am I doing wrong here?
 
P

Paul Rubin

Josef Wolf said:
dir(md5) shows that md5 don't have an __init__() method so I tried to use
its new(), with the same result. What am I doing wrong here?

md5 isn't set up to be subclassed like that. Better make a new
md5file class and have an md5 instance inside your md5file instances.
You can make a __getattr__ method to forward operations on md5file
instances to the internal md5 object. There's probably also some
metaclass tricks you could use to make that happen automagically.
 
E

Erik Max Francis

Josef said:
import md5

class md5file(md5): ...
dir(md5) shows that md5 don't have an __init__() method so I tried to
use
its new(), with the same result. What am I doing wrong here?

md5 is a module, not a class!
 
S

Shalabh Chaturvedi

Josef said:
Hello!

I'd like to create a class to calculate md5's of a file. So I thought, I'd
derive from the md5 class. I came up with following code:

#!/usr/bin/python

import md5

class md5file(md5):
def __init__(self, filename):
md5.__init__(self)
f=file(filename,"r")
for l in f:
self.update(l)
f.close()

print md5file("/etc/passwd").hexdigest()

But running this gives me the following error:

Traceback (most recent call last):
File "py/t.py", line 5, in ?
class md5file(md5):
TypeError: function takes at most 2 arguments (3 given)

dir(md5) shows that md5 don't have an __init__() method so I tried to use
its new(), with the same result. What am I doing wrong here?

Why subclass? You could just get the md5 object by doing:

from md5 import md5
m = md5(open(filename).read())

Simple is better than complex.
 
E

Erik Max Francis

Shalabh said:
Why subclass? You could just get the md5 object by doing:

from md5 import md5
m = md5(open(filename).read())

Simple is better than complex.

If you really want to mix the old md5 functionality with the new, a
class containing an md5 instance would be a fine solution.
 

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

Forum statistics

Threads
473,764
Messages
2,569,566
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top