当为了返回字典而调用类时,字典的值是对象在内存中的位置,这不是我需要的。an image of what I am recieving
class Element:
def __init__(self,name,number,symbol,weight):
self.__name = name
self.__number = number
self.__symbol = symbol
self.__weight = weight
def getname(self):
return self.__name
def getnumber(self):
return self.__number
def getsymbol(self):
return self.__symbol
def getweight(self):
return self.__weight
def __str__(self):
return self.__name + ' ' + str(self.__number) + ' ' + self.__symbol + ' ' + str(self.__weight)
class PeriodicTable():
def __init__(self,file):
lines = open(file,"r").read().split("\n")
self.ElementsDictionary = {}
for line in lines[1:]:
tokens = line.split(",")
name, number, symbol, weight = tokens[0], tokens[1], tokens[2], tokens[3]
self.ElementsDictionary[symbol] = Element(name,number,symbol,weight)
def __str__(self):
return str(self.ElementsDictionary)
x = PeriodicTable("elements.txt")
print(x)
答案 0 :(得分:0)
在这一行中看起来像是一个问题。
self.ElementsDictionary[symbol] = Element(name,number,symbol,weight)
在这里,以字符串格式存储对象,它将解决您的问题
self.ElementsDictionary[symbol] = str(Element(name,number,symbol,weight))