jeudi 7 novembre 2019

Python decorator for random generator?

I am doing some coding homework and need to use a class with two functions first function to generate a random number and second function to set the value. I understand that the result should be such that getter output is equal to setter output, but they are not the same as I think setter activates getter the second time before printing result. I think I need to use decorators to solve this problem so that is how I approached it.

class RandNum(object):

random.seed(0)

def __init__(self):

    self.num = self.getNum


@property
def getNum(self):

    return random.randint(0,20)

@getNum.setter
def setNum(self,num):

     self.num = num

After printing

randnum = RandNum()
for i in range(3):
    print("getter: ", randnum.getNum)
    print("setter: ", randnum.setNum)

I get

getter:  13
setter:  1
getter:  8
setter:  16
getter:  15
setter:  12

So my getter and setter are always different. How can I make them the same? Been working on it for a few days and to no avail yet, so would really appreciate the help.




Aucun commentaire:

Enregistrer un commentaire