Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

class

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
like image 657
zebralamy Avatar asked Nov 09 '17 19:11

zebralamy


1 Answers

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

env = Environment()
nodes = env.setEnv

that is no the same as:

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

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

like image 82
A Monad is a Monoid Avatar answered Sep 30 '22 08:09

A Monad is a Monoid