Search code examples
pythonreturnnonetype

Problem with Python returning a NoneType object instead of the Object


I'm struggling with a python class method returning a NoneType value instead of the desired object. I'm working with reinforcement learning a need to create a 2D map of tiles but my get_tile method keeps return NoneType

class TileEnvironment:

    def __init__(self):
        self.envir = []

        # creates a tile for each position
        for i in range(0, 4):
            for j in range(0, 4):
                self.envir.append(Tile(i, j, 0))

        # Changes tileTypes for specific program
        self.get_tile(2, 3).edit_type(2)
        self.get_tile(1, 2).edit_type(0)
        self.get_tile(2, 1).edit_type(1)
        self.get_tile(2, 2).edit_type(1)

    def get_tile(self, x, y):
        for i in range(len(self.envir)):
            if self.envir[i].x == x & self.envir[i].y == y:
                return self.envir[i]

here's the stack trace I'm getting

Traceback (most recent call last):
  File "C:\Users\Brian\Desktop\SURP\Pycharm\Week1_QTables\main.py", line 163, in <module>
    main()
  File "C:\Users\Brian\Desktop\SURP\Pycharm\Week1_QTables\main.py", line 128, in main
    envir = TileEnvironment()
  File "C:\Users\Brian\Desktop\SURP\Pycharm\Week1_QTables\main.py", line 48, in __init__
    self.get_tile(2, 3).edit_type(2)
AttributeError: 'NoneType' object has no attribute 'edit_type'

I can still access the tiles in envir but when the method passes it, the program breaks.

Thanks in advance for your help and consideration


Solution

  • You need to use and instead of &

    if self.envir[i].x == x and self.envir[i].y == y:
    

    Keep in mind that in Python the boolean and operator is and and not & or && as in other programming languages. Actually, in Python & is the and bitwise operator.

    Also keep in mind that when a function/method reaches the end of its body, if there are not explicit return statements, None is returned by default.