The problem is in your playerMovement method. You are creating the string name of your room variables (ID1, ID2, ID3):

letsago = "ID" + str(self.dirDesc.values())

However, what you create is just a str. It is not the variable. Plus, I do not think it is doing what you think its doing:

>>>str({'a':1}.values())
'dict_values([1])'

If you REALLY needed to find the variable this way, you could use the eval function:

>>>foo = 'Hello World!'
>>>eval('foo')
'Hello World!'

or the globals function:

class Foo(object):
    def __init__(self):
        super(Foo, self).__init__()
    def test(self, name):
        print(globals()[name])

foo = Foo()
bar = 'Hello World!'
foo.text('bar')

However, instead I would strongly recommend you rethink you class(es). Your userInterface class is essentially a Room. It shouldn't handle player movement. This should be within another class, maybe GameManager or something like that.

Answer from BeetDemGuise on Stack Overflow
🌐
Reddit
reddit.com › r/learnpython › 'str' object has no attribute error?
r/learnpython on Reddit: 'Str' object has no attribute error?
November 9, 2023 -

I have some experience with programming in Java, C++, etc. and I am trying to write a simple "To-Do List" program to get used to Python. I'm running into the error: str object has no attribute "completed" when trying to iterate over the list of tasks, check their completion status, and display them.

Here are some relevant pieces of the program:

Constructor for the Task class

def __init__(self, task_name):

self.task_name = task_name

self.completed = False

In the ToDoList class (which holds a list of the task instances created by the user) this is the iteration throwing the error in question:

for idx, task in enumerate(self.tasks, start=1):

status = "Completed" if task.completed else "Incomplete"

print(f"{idx}. {task.task_name} - {status}")

I thought, potentially the problem lies in the fact that the enumerate function is grabbing the string value of the task instance, rather than the object itself, so maybe I can iterate over it the old fashioned way and get around it. So I tried it like this:

counter = 1

for task in self.tasks:

status = "Completed" if task.completed else "Incomplete"

print(f"{counter}. {task.task_name} - {status}")

counter += 1

Yet, it throws the same error. I know there is something I am missing or not understanding correctly here. What is it?

Thanks!

Discussions

python - AttributeError 'str' object has no attribute - Stack Overflow
I am new to python and I get stuck in this error. I want to print names and years of birth of animals in team in an order by the name. Now I am keeping getting printing years and names but without ... More on stackoverflow.com
🌐 stackoverflow.com
December 4, 2017
django - AttributeError at / 'str' object has no attribute 'objects' - Stack Overflow
I am new to Django. I am working on a project that uses weather API to get the weather.Everything was working fine until models.py was made and imported city on views.py I use ver. 1.11.13 models... More on stackoverflow.com
🌐 stackoverflow.com
How do i fix this : AttributeError: 'str' object has no attribute 'current'
It says AttributeError: 'str' object has no attribute 'current'. That error isn't coming from this function. More on reddit.com
🌐 r/learnpython
11
0
December 7, 2023
AttributeError: 'str' object has no attribute 'get' when sending with batch_id
EDIT: Condensed all example code way down Issue Summary The Mail object invokes the get() method upon sending. This in turn creates a JSON representation of the mail object, by calling _get_or_none(self.attr) for all provided attributes.... More on github.com
🌐 github.com
6
May 20, 2021
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-fix-attributeerror-object-has-no-attribute
How to fix AttributeError: object has no attribute - GeeksforGeeks
July 23, 2025 - This section is reserved for our understanding in the common scenarios in which we encounter the "AttributeError". ... We are defining a Dog class with a constructor to initialize the name attribute. The def __init__(self, name) is the class's constructor method. It takes two parameters, self (the instance being created) and name (the dog's name). Inside the constructor, we are initializing the name attribute of the Dog object with the value provided as name.
🌐
DaniWeb
daniweb.com › programming › software-development › threads › 285737 › attributeerror-str-object-has-no-attribute
python - AttributeError: 'str' object has no attribute [SOLVED] | DaniWeb
In berrol.setLocation(berrol, well), the first argument after self is redundant (methods get self automatically), and the second looks like a place name, not a Place object. Pick one representation and stick to it. A simple pattern is: Person.set_location(place_key: str) and store places in a dict by key. Also note that your occupants is a tuple; tuples are immutable, so calling .remove on it will raise an AttributeError.
🌐
Brainly
brainly.com › engineering › college › what does "str object has no attribute" mean in python?
[FREE] What does "str object has no attribute" mean in Python? - brainly.com
Also, ensure that you are using ... 'str' object has no attribute" is an error message that appears when you try to access an attribute that doesn't exist on a string object....
🌐
Bobby Hadz
bobbyhadz.com › blog › python-attributeerror-str-object-has-no-attribute
AttributeError: 'str' object has no attribute 'X in Python | bobbyhadz
April 8, 2024 - The Python "AttributeError: 'str' object has no attribute" occurs when we try to access an attribute that doesn't exist on string objects.
Find elsewhere
🌐
Itsourcecode
itsourcecode.com › home › attributeerror: ‘str’ object has no attribute ‘values’
attributeerror: 'str' object has no attribute 'values' [SOLVED]
March 31, 2023 - Traceback (most recent call last): ... this error, you will need to use the correct spelling values attribute on a valid object like a dictionary or pandas dataframe, and not on a string object....
🌐
Reddit
reddit.com › r/learnpython › how do i fix this : attributeerror: 'str' object has no attribute 'current'
r/learnpython on Reddit: How do i fix this : AttributeError: 'str' object has no attribute 'current'
December 7, 2023 -

There is something wrong with this function. It shows no errors, but when I try to run it, It says AttributeError: 'str' object has no attribute 'current'. (BTW, i am trying to run it as a flet on spyder)

def leapyears(e):

days_in_month = {1: 31, 3: 31, 4: 30, 5:31, 6: 30, 7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31 }

month = int(EnterMonth_text.value)

year = int(EnterYear_text.value)

if year % 100 == 0:

if year % 400 == 0:

leap_year = True

elif year % 4 == 0:

leap_year = True

else:

leap_year = False

if month == 2 :

if leap_year:

days_in_month[2] = 29

else:

days_in_month[2]= 28

output_textfield.value= days_in_month[month]

page.update()

🌐
Esri Community
community.esri.com › t5 › arcgis-api-for-python-questions › str-object-has-no-attribute › td-p › 1053478
Solved: 'str' object has no attribute - Esri Community
September 14, 2021 - The clone_items function takes a list of Items. It seems like you are passing in the string item ids instead.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-attributeerror
Python: AttributeError - GeeksforGeeks
July 12, 2025 - Traceback (most recent call last): File "/home/2078367df38257e2ec3aead22841c153.py", line 3, in string = "The famous website is { }".fst("geeksforgeeks") AttributeError: 'str' object has no attribute 'fst' Example 3: AttributeError can also be raised for a user-defined class when the user tries to make an invalid attribute reference. ... # Python program to demonstrate # AttributeError class Geeks(): def __init__(self): self.a = 'GeeksforGeeks' # Driver's code obj = Geeks() print(obj.a) # Raises an AttributeError as there # is no attribute b print(obj.b)
🌐
GitHub
github.com › sendgrid › sendgrid-python › issues › 993
AttributeError: 'str' object has no attribute 'get' when sending with batch_id · Issue #993 · sendgrid/sendgrid-python
May 20, 2021 - This in turn creates a JSON representation of the mail object, by calling _get_or_none(self.attr) for all provided attributes. While the functionality works correctly more most attributes, if one attaches a batch_id to the Mail object, the _get_or_none method throws an AttributeError: 'str' object has no attribute 'get'
Published   May 20, 2021
Author   jordaniza
🌐
PyTorch Forums
discuss.pytorch.org › t › attributeerror-str-object-has-no-attribute-items › 144286
AttributeError: 'str' object has no attribute 'items' - PyTorch Forums
February 16, 2022 - I don’t know why I get this error. model.train() for imgs, targets, image_ids in train_loader: imgs = list(imgs.to(device) for img in imgs) targets = [{k: v.to(device) for k, v in t.items()} for t in targets] loss_dict = model(imgs, targets) losses = sum(loss for loss in loss_dict.values()) loss_value = losses.item() optimizer.zero_grad() losses.backward() optimizer.step() for epoch in range(num_epoch): print('Epoch {}/{}'.format(epoch, num_e...
🌐
Edureka Community
edureka.co › home › community › categories › others › error attributeerror str object has no...
Error AttributeError str object has no attribute row | Edureka Community
April 4, 2023 - I have code: def add_to_database(object_name, value): workbook = openpyxl.load_workbook(DATABASE_FILE) worksheet ... row, column = 2).value += value
🌐
Django Forum
forum.djangoproject.com › using django
AttributeError: 'str' object has no attribute 'field' - Using Django - Django Forum
September 24, 2021 - Im trying to make a custom change password page but the page with the “PasswortConfirmView” prints this error Internal Server Error: /reset/confirm/MQ/atg5tq-aa6bcab1c34d1228cdd1970aaaa45252/ Traceback (most recent call last): File "C:\Users\Finn\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Finn\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\ba...
🌐
GitHub
github.com › stanfordnlp › dspy › issues › 568
Error when running Evaluate: 'str' object has no attribute '_store' · Issue #568 · stanfordnlp/dspy
March 6, 2024 - class Summarizer(dspy.Module): def __init__(self): super().__init__() self.summarizer = dspy.Predict('transcript -> summary') def forward(self, transcript): return dspy.Prediction(summary=self.summarizer(transcript=transcript))
Author   gramster
🌐
Fast.ai
forums.fast.ai › fastai › fastai dev
AttributeError: 'str' object has no attribute 'to' - fastai dev - fast.ai Course Forums
October 7, 2018 - I am not 100% sure that this is an error that you guys will care about, but I built a DataBunch using two datasets from a class I built. The issue might be my understanding of datasets, but here is what my dataset class looks like: class DCMImageDictDataset(LabelDataset): "Abstract `Dataset` containing images." def __init__(self, dictionary): self.patientID = list(dictionary.keys()) #self.imgs = trn_dict #self.y = np.array(y) self.images = [] sel...
Top answer
1 of 2
1

Your code has multiple problems - not just the one that has been answered by @Tanishq

You entire approach is not ideal. It's much better to limit your Student class to storing data and handling its representation. Acquisition of the data should be dealt with separately.

Something like this:

from typing import Any

class Student:
    def __init__(self, name: str):
        self._name: str = name
        self._data: dict[str, float] = {}
        
    def __add__(self, __value: Any) -> 'Student':
        subject, score = __value
        self._data[subject] = score
        return self

    def __str__(self):
        r = [self._name]
        for subject, score in self._data.items():
            r.append(f'{subject} -> {score}')
        return '\n'.join(r)

name = input('Student name: ')
student = Student(name)
n = int(input('Number of subjects: '))
for _ in range(n):
    subject = input('Subject name: ')
    score = float(input('Score: '))
    student += (subject, score)
print(student)

Console example:

Student name: John
Number of subjects: 2
Subject name: English
Score: 65
Subject name: Geography
Score: 58
John
English -> 65.0
Geography -> 58.0

Note:

Numeric input validation omitted for brevity

2 of 2
0

Here is one way of doing what you want

class student(object):
    def __init__(self, standard: int, name: str, age: int, address: str):
       self.standard = standard
       self.name = name
       self.age = age
       self.address = address
       
       self.calc()

    def calc(self):
        self.subject = []
        self.score = []

        N = (int)(input('Please enter number of Subjects: '))

        for i in range(N):
            item = input('Enter Subject name: ').upper()
            self.subject.append(item)
        
        for i in range(len(self.subject)):
            item = input(f'Please Enter the score for {self.subject[i]}: ')
            self.score.append(item)


student1 = student(standard=10, name="foo", age=13, address="bar")

Your error:

  • You are directly calling the calc function of the class, student, without instantiating it. (You can checkout staticmethods in Python if you still want to do this.)
  • The self is then treated as a variable name, and since you pass '' as the value of self, it is inferred to be a string.
  • This is why you get the error, that the str has no attribute name - because the self is a string and not the instance.

Some notes:

  • You need to instantiate the class, student, and pass in the required arguments (as shown in the last line of my solution).
  • You can merge the print before the input into one, as shown.
  • You can merge the calc function with __init__, as mentioned in the comments.
  • You are returning within the for loop, after you do self.subject.append(...). This will not let to have more than 1 subject, and your scores will always be empty - since the function calc will never reach the score handling section.
  • You might want to look at exception handling to handle the input of number of subjects, here.
🌐
GitHub
github.com › fastai › fastai › issues › 2758
AttributeError: 'str' object has no attribute '__stored_args__' · Issue #2758 · fastai/fastai
September 5, 2020 - $ python3 -c "from fastai.basics import *" Traceback (most recent call last): File "<string>", line 1, in <module> File "/home/m/anaconda3/lib/python3.8/site-packages/fastai/basics.py", line 1, in <module> from .data.all import * File "/home/m/anaconda3/lib/python3.8/site-packages/fastai/data/all.py", line 5, in <module> from .transforms import * File "/home/m/anaconda3/lib/python3.8/site-packages/fastai/data/transforms.py", line 230, in <module> class Categorize(DisplayedTransform): File "/home/m/anaconda3/lib/python3.8/site-packages/fastai/data/transforms.py", line 232, in Categorize loss_fu