I do that in python:
class Datos:
def __init__(self):
self.indice = int()
self.nombre = str()
def GuardarMontaña(fich: str, datos: Datos)->bool:
cad = fich.readline()
while cad != "":
if cad == '':
ok = False
else:
ok = True
linea1 = cad.split()
datos.indice = int(linea1[0])
datos.nombre = linea1[1]
cad = fich.readline()
return ok
def main():
try:
f = open("Pr8_C_montanas.txt", encoding = 'UTF-8')
except:
print("No se ha podido abrir el fichero para lectura.")
else:
datos = Datos()
if(GuardarMontaña(f, datos)):
print(datos)
else:
print("Impsible leer datos.")
if __name__ == '__main__':
main()
I was trying that program and I don't know why, <__main__.Datos object at 0x00000259566AFE50>
, appears on my screen.
I have designed this program for a class exercise, in which we have a file with lines that contain the index and the name of a mountain, and we must save the data in a register where we can access it later.
CodePudding user response:
Datos class doesnt have __str__
method, so print(datos)
outputs <main.Datos object at 0x00000259566AFE50>,
try:
class Datos:
def __init__(self):
self.indice = int()
self.nombre = str()
def __str__(self):
return "indice: " str(self.indice)
CodePudding user response:
When an object is printed, it's converted to a string. What you're seeing here is the default implementation of __str__
that essentially prints the location of the object in the program's memory. If you want something more meaningful, you can (and should) override it. E.g.:
def __str__(self):
return f'{self.indice}: {self.nombre}'