获取对象的值而不是它在内存中的位置
Getting the value of an object instead of its location in memory
我正在 Python 学习 OOP,我正在制作一个有 5 个骰子的游戏。我制作了 Dado
对象来代表我的骰子,并制作了 GeraDado
对象来实际创建 Dado
对象。如果我创建一个对象,例如 d1 = GeraDado()
,我可以使用 d1.valor()
方法打印它的值,但是如果我尝试将它的值附加到列表或字典中,它 returns None
.如果我这样做 print(d1)
它 return 对象在内存中的位置而不是值。我怎样才能使 return 成为 d1 = GeraDado()
值而不是使用 d1.valor()
方法,它只是在屏幕上打印值?
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)
你的 Dado.valor
和 GeraDado.dado
方法只打印骰子的值,它们实际上并不 return 它,相反,使它们 return 使用return
语句:
Dado.valor
:
def valor(self):
return self.__valor
GeraDado.dado
:
def dado(self):
return self.__dado.valor()
两个小建议:
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
我正在 Python 学习 OOP,我正在制作一个有 5 个骰子的游戏。我制作了 Dado
对象来代表我的骰子,并制作了 GeraDado
对象来实际创建 Dado
对象。如果我创建一个对象,例如 d1 = GeraDado()
,我可以使用 d1.valor()
方法打印它的值,但是如果我尝试将它的值附加到列表或字典中,它 returns None
.如果我这样做 print(d1)
它 return 对象在内存中的位置而不是值。我怎样才能使 return 成为 d1 = GeraDado()
值而不是使用 d1.valor()
方法,它只是在屏幕上打印值?
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)
你的 Dado.valor
和 GeraDado.dado
方法只打印骰子的值,它们实际上并不 return 它,相反,使它们 return 使用return
语句:
Dado.valor
:
def valor(self):
return self.__valor
GeraDado.dado
:
def dado(self):
return self.__dado.valor()
两个小建议:
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