class returns <bound method …> instead of the value I returned (python)

Question:

I’m trying to get the return from the class I defined but it keeps returning <bound method Environment.setEnv of <__main__.Environment object at 0x0000022E86895828>> instead of the value I returned.

As you can see below, my code creates row*column grid of connected nodes which is however gathered in a simple list nodes.

What I want to do is to print this return value nodes to check everything’s in place. However, when I do this,

env = Environment()
nodes = env.setEnv
print(nodes)  

It does not return the list of nodes which I expect to look like [0000x00efc, se0fdsf000cx, 000dfsecsd ….]

I don’t think I understand how to return a variable used in a class.
I looked up my textbook but it just simply doesn’t have any example that can be applied to this situation.

class Node:
    def __init__(self, data ="0", up = None, right = None, down = None, left = None, visited = 0):
        self.data = data
        self.up = up
        self.right = right
        self.down = down
        self.left = left
        self.visited = visited


class Environment:
    def __init__(self, row = 10, column = 10):
        self.row = row
        self.column = column

    def setEnv(self):
        nodes = []
        for i in range(self.row*self.column): 
            nodes.append(Node())

        for i in range(0,self.row*self.column,self.column): 
            for j in range(self.column - 1):
                nodes[i+j].right = nodes[i+j+1]
                nodes[i+j+1].left = nodes[i+j]

                if i < (self.row-1)*self.column : nodes[i+j].down = nodes[i+j+self.column]  #맨 마지막 row제외
                if i > 0 : nodes[i+j].up = nodes[i+j-self.column]  

        return nodes
Asked By: zebralamy

||

Answers:

This is a very common mistake in python, and sadly easy to reproduce and fall for it, but once you do it, you will never do it again:

env = Environment()
nodes = env.setEnv

that is not the same as:

env = Environment()
nodes = env.setEnv()

With () , you are invoking a function in python, without them, you are just returning the reference to the function, but not the "execution of the function".

Answered By: Damian Lattenero
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.