SHA-based subclass for random module

Josiah Carlson jcarlson at nospam.uci.edu
Sat Mar 20 01:35:34 CET 2004


>>>What's Random.random(self) supposed to do?
>>
>>Generate a random number using the Mersenne Twister random number
>>generator.
> 
> According to the Random doc, Random.random() doesn't take an argument,
> so I'm asking what the "self" is for.

>>>But doesn't support all the operations specified in the Random API.
>>>What's up with that?
>>
>>That is what the subclass was for:
>> > class MD5Random(Random):
> 
> But the methods in the superclass don't do anything to manage the state
> of subclass instances.

Perhaps you should spend some more time learning how Python classes work.

Random is a class.
Random.random is an unbound class method.
Random.random(self) calls the unbound class method 'Random.random' with 
the first argument being the MD5Random instance.

You should satisfy yourself that the below is correct behavior for 
Python classes.

 >>> class A:
...     def blah(self):
...         print self.__class__
...
 >>> class B(A):
...     def blah(self):
...         print "I'm in B, calling A"
...         A.blah(self)
...
 >>> a = A()
 >>> a.blah()
__main__.A
 >>> b = B()
 >>> b.blah()
I'm in B, calling A
__main__.B

Can you figure out why the following is also correct?

 >>> class C:
...     def blah(self):
...         print "I'm in C, calling A"
...         A.blah(self)
...
 >>> c = C()
 >>> c.blah()
I'm in C, calling A
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
   File "<stdin>", line 4, in blah
TypeError: unbound method blah() must be called with A instance as first 
argument (got C instance instead)


Perhaps now you understand why he can use Random.random(self) in the 
earlier version, and Random.getrandbits(self, 128) in the current version.

  - Josiah



More information about the Python-list mailing list