Hi, i am currently trying to learn how to program in python and i have been doing ok until now! I am confused about classes objects and methods, i understand most of how they work.

In a question task I am asked to create some code for a die (singular of dice), and it says that i have to include the following:

class Die(object):

"Die.__init__(self)" to initialise an attribute called 'value' to 1.

I've seen things like def__init__(self) before but I don't get Die.__init__, does anyone know what this means? And initialising a value to 1 through this, does that just mean I'm writing that the value is 1 or is this similar to a function?? V.confused!


Another thing I've got to include is Die.__str__(self) again with the Die.__str__ i am unsure of what this means! It says this should return a message saying that it's an object of the Die class and stating the current value.


And finally I get asked about Die.throw(self), ive noticed this doesn't have the __ underscore's so i'm thinking this is something else? This one is supposed to set the value attribute at a random integer in the range 1 to 6 and return that value. when it says return that value i think function, am i thinking right?


don't worry if you can't help however if you can i would appreciate any tips and hints!

thanks very much

Jay:icon_redface:

Recommended Answers

All 2 Replies

I suggest you study your class notes more carefully. Here is a short example that might help you:

class Die(object):

    def __init__(self, v):
        """
        the constructor of the class
        self 'carries' the instance
        dice initially has value v
        """
        self.value = v
        
    def __str__(self):
        """overload __str__ will be used in print statement"""
        s = "dice shows " + str(self.value)
        return s

    def throw(self):
        """throw one dice here to show 1 - 6"""
        import random
        self.value = random.randint(1, 6)


# create an instance of class Die and set initial value to 1
# uses Die.__init__(self, 1) where self would be the instance q
q = Die(1)

print q  # dice shows 1

q.throw()

print q  # eg. dice shows 3

q.throw()

print q  # eg. dice shows 6

Hi, thanks very much, i think i understand the concept of it now. I didn't realise that the Die.__init__ suggested to use a function however i will now remember this for the future.
I also just read a previous post on inheritance in this forum which has helped. I don't have many notes on classes at the moment, I am hoping to take a proper course in Python soon I enjoy programming!

Thanks for your help.
Kind regards, Jay

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.