Usando um analisador Python Gedcom: recebendo saída ruim (Instância de GedCom.Element em 0x00…)
Pergunta
Sou novo no Python e posso dizer que minha experiência de programação é nominal em comparação com muitos de vocês. Preparem-se :)
Eu tenho 2 arquivos. Um analisador GEDCOM escrito em Python que encontrei de um usuário neste site (gedcom.py - http://ilab.cs.byu.edu/cs460/2006w/assignments/program1.html) e um arquivo GEDCOM simples que eu puxei de heiner-eichmann.de/gedcom/gedcom.htm. Adivinha quem está tendo problemas para montar 2 e 2? Esse cara...
Aqui está um trecho de código seguido pelo que fiz até agora.
class Gedcom:
""" Gedcom parser
This parser is for the Gedcom 5.5 format. For documentation of
this format, see
http://homepages.rootsweb.com/~pmcbride/gedcom/55gctoc.htm
This parser reads a GEDCOM file and parses it into a set of
elements. These elements can be accessed via a list (the order of
the list is the same as the order of the elements in the GEDCOM
file), or a dictionary (the key to the dictionary is a unique
identifier that one element can use to point to another element).
"""
def __init__(self,file):
""" Initialize a Gedcom parser. You must supply a Gedcom file.
"""
self.__element_list = []
self.__element_dict = {}
self.__element_top = Element(-1,"","TOP","",self.__element_dict)
self.__current_level = -1
self.__current_element = self.__element_top
self.__individuals = 0
self.__parse(file)
def element_list(self):
""" Return a list of all the elements in the Gedcom file. The
elements are in the same order as they appeared in the file.
"""
return self.__element_list
def element_dict(self):
""" Return a dictionary of elements from the Gedcom file. Only
elements identified by a pointer are listed in the dictionary. The
key for the dictionary is the pointer.
"""
return self.__element_dict
Meu pequeno roteiro
Importar GEDCOM
g = gedcom ('c: tmp test.ged') // estou no windows
imprimir g.element_list ()
A partir daqui, recebo um monte de saída "GedCom.Element Instância em 0x00 ..."
Não sei por que estou recebendo essa saída. Eu pensei que, de acordo com o método element_list, uma lista formatada seria retornada. Eu pesquisei e pesquisei neste site. A resposta provavelmente está me encarando, mas eu esperava que alguém pudesse apontar o óbvio.
Muito apreciado.
Solução
someclass instance at 0xdeadbeef
é o resultado do padrão __repr__
Método para classes que não definem uma, como aparentemente aula gedcom.Element
Não, o problema é apenas com você imprimir uma lista dessas instâncias. Se essa classe define __str__
, você poderia
for x in g.element_list():
print x
mas se não acontecer, isso também dará saída semelhante (como __str__
"Padrões para" __repr__
). O que você quer Faz com esses elementos, por exemplo, um método que sua classe faz oferta?
Outras dicas
Não há nada errado ou incomum nessa saída. Porque gedcom.Element
não definiu um __repr__
, imprimir a lista mostrará o padrão __repr__
. Se você quiser acessar um atributo específico em cada elemento, você pode tentar:
print [element.some_attribute for element in g.element_list()]
editar: Aha, olhei sobre a fonte que você forneceu. De fato define um __str__
, mas não __repr__
. Aqui está o que você quer, provavelmente:
for element in g.element_list()
print element