Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
216 views
in Technique[技术] by (71.8m points)

python - Trying to Print values but getting memory location instead

I have a function below which I want to output lines of values relating to 'O', instead it prints the location of these values, how do I amend this? allReactions is an empty array initially. I've tried a number of ways to get around this but keep getting errors. Also I think my methods are less efficient than can be.

allReactions = []

reactionFile = "/Databases/reactionsDatabase.txt"

with open(reactionFile) as sourceFile:
    for line in sourceFile:

        if line[0] == "!" or len(line.strip()) == 0: continue

        allReactions.append(Reaction(line, sourceType="Unified Data"))


def find_allReactions(allReactions, reactant_set):
    reactant_set = set(reactant_set) 
    relevant_reactions = []
    previous_reactant_count = None

    while len(reactant_set) != previous_reactant_count:
        previous_reactant_count = len(reactant_set)

        for reaction in allReactions:
            if set(reaction.reactants).issubset(reactant_set):
                relevant_reactions.append(reaction)
                reactant_set = reactant_set.union(set(reaction.products))

    return relevant_reactions

print find_allReactions(allReactions, ["O"])
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You are trying to print a list of Reaction objects. By default, python prints a class object's ID because it really doesn't have much to say about it. If you have control over the class definition, you can change that by adding __str__ and __repr__ method to the class.

>>> class C(object):
...     pass
... 
>>> print C()
<__main__.C object at 0x7fbe3af3f9d0>

>>> class C(object):
...     def __str__(self):
...             return "A C Object"
... 
>>> print C()
A C Object
>>>                                                                                         

If you don't have control of the class... well, the author didn't implement a pretty view of the class. You could create subclasses with the methods or write a function to pull out the stuff you want.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...