Home > Enterprise >  Getting the value of an object instead of its location in memory
Getting the value of an object instead of its location in memory

Time:10-27

I'm studying OOP in Python and I'm making a game with 5 dices. I made the Dado object to represent my dices and the GeraDado object to actually create the Dado object. If I create an object such as d1 = GeraDado() I can print its value using the d1.valor() method but if I try to append its value to a list or dictionary it returns None. If I do print(d1) it returns the object's location in memmory and not the value. How can I make it return the d1 = GeraDado() value instead of using the d1.valor() method, that just prints the value on screen?

from random import randint

class Dado:
    def __init__(self, valor):
        self.__valor = valor

    def valor(self):
        print(self.__valor)
        
class GeraDado:
    def __init__(self):
        self.__dado = Dado(randint(1,6))

    def dado(self):
        self.__dado.valor()

d1 = GeraDado()
print(d1)

CodePudding user response:

Your Dado.valor and GeraDado.dado methods only print the value of the die, they don't actually return it, instead, make them return the value using the return statement:

Dado.valor:

def valor(self):
    return self.__valor

GeraDado.dado:

def dado(self):
    return self.__dado.valor()

CodePudding user response:

Two little suggestions:

class Dado:
    # ...
    def valor(self):
        return self.__valor  
        # 1. return stuff!
        # Don't fall in love with print. It's just a debugging side-effect
      

class GeraDado:
    # ... 
    def dado(self):
        return self.__dado.valor()  # 1. again: return!

    # 2. implement a __str__ method. 
    # This is your class's representation that is used by print
    def __str__(self):  
        return str(self.dado())

>>> d1 = GeraDado()
>>> print(d1)
1
  • Related