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,69919 gold badges32 silver badges39 bronze badges
asked Apr 11, 2014 at 16:41

1 Answer 1

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
>>>
answered Apr 11, 2014 at 16:42
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.