Understanding Python Functions

jskfan
jskfan used Ask the Experts™
on
Understanding Python Functions

I have this Python code :
import random
class Dice:
    def Roll(self):
     first=random.randint(1,6)
     second=random.randint(1,6)
     return  first,second


dice=Dice()
print(dice.Roll())

Open in new window


I would like to know the meaning of Self in : the function Roll. is it a parameter that needs an argument passed to it ? if so what argument was it passed to it in the above example?

I also want to understand the Return keyword.  in the example above the result from variables first and second will be returned but where does it get stored ?
it should be store in the function Roll, but where ? in the Self parameter ?

Any clarification will be very much appreciated.


Thank you
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
The Roll is not a plain function. It is the method of the class Dice. The self is the first parameter that is usually implicit in other OOP languages. It must be used here explicitly in Python. The name self is by convention, but you should not use any other name for the purpose.

When you call dice.Roll() then from inside the Roll, the self is assigned to the same value as dice. In other words, the argument refers to itself (hence the name). In some OOP languages, it is called this. Python makes this mechanism more visible, more explicit. Actually, you can think about Dice as about namespace, and about Roll as about a plain function in the namespace. And you can do exactly the same call as dice.Roll() using also the syntax Dice.Roll(dice) -- that should make the relation between dice and self more obvious.

For the return command... The return is unrelated to self. The result is not stored anywhere in your example. It is just printed. If you want to use the result for other purpose later (not only for printing), you have to assign the result of the call first. You have to modify the code like this:
v1, v2 = dice.Roll()
print(v1, v2)
print(v1)
print(v2)

Open in new window

or
t = dice.Roll()
print(t)
print(t[0])
print(t[1])

Open in new window


Off topic: It is (highly) recommended to use 4 spaces for each indentation level.
Top Expert 2014

Commented:
You don't really need a class for this.  Your Roll function can stand on its on without the need for a class.

Author

Commented:
Thank you

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial