How do I refer to any object in a function

I’ve been learning Python as my first programming language for a couple of days, and as my first project I wanted to write a text game.
I’m using the adventurelib module. It allows me to specify what the programme should do when user enters given instruction. I want a player to be able to pass a line “walk to ITEM”, which will result in the item being in the player’s range. The item is a part of the Item class whose objects have the “in_range” variable. I want to place the items name before “.in_range” so that it changes the boolean value of in_range for the item the player chooses.

Here’s the code:

class Item:
    def __init__(self, is_working, is_used, in_range):
        self.is_working = is_working
        self.is_used = is_used
        self.in_range = in_range

chair = Item(True, False, False)

@when ("walk to ITEM")
def walk_to(item):

    item.in_range = True
    print(f"You walk to the {item}"

“item.in_range” = True gives me the following error: “AttributeError: ‘str’ object has no attribute ‘in_range’”
I thought i could pass “item.in_range”, but this obviously isn’t the case.

Sorry for my bad English


EDIT: After re-reading your post. and reading some of the documentation of adventurelib. Your function is taking a string as it’s argument. then you are trying to trying to access in_range on it. The String object won’t have that attribute. To refer to the in_range attribute on the current Object, I would attempt the following:

... # omitted class code

@when("walk to ITEM")
def walk_to(item):
    if self.in_range:
        print(f"You walk to the {item}")

Let us know how that works. Then when you post more code in your next posts surround them with two sets of three backticks. It will help us read your code better.

like this:

# put your code here
1 Like