1

I am teaching myself Python and hit a roadblock with classes and modules. The code below is something that you would probably never write, but I would like to just understand my error.

import random

class GetRandom:
    def __init__(self):
        self.data = ""

    def ranNumber():
        return random.random()

b = GetRandom()
bnum = b.ranNumber
print bnum

The output I am getting is:

<bound method GetRandom.ranNumber of <__main__.GetRandom instance at 0x7fe87818df38>>

I had expected a random number between 0 and 1. What am I doing wrong?

Thanks

CDspace
  • 2,639
  • 18
  • 30
  • 36
neilhu
  • 35
  • 2

1 Answers1

2

There are two problems here:

  1. You forgot to actually invoke GetRandom.ranNumber. Add () after it to do this:

    bnum = b.ranNumber()
    
  2. You need to make GetRandom.ranNumber accept the self argument that is passed implicitly when you invoke the method:

    def ranNumber(self):
        return random.random()
    

Once you address these issues, the code works as expected:

>>> import random
>>> class GetRandom:
...     def __init__(self):
...         self.data = ""
...     def ranNumber(self):
...         return random.random()
...
>>> b = GetRandom()
>>> bnum = b.ranNumber()
>>> print bnum
0.819458844177
>>>
Community
  • 1
  • 1