Python Forum

Full Version: Classes error
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hey,

I have some trouble with my code. I'm practicing on Classes in PyCharm, and was trying to create a system that spelled the names of everyone registered. However, I get an error message when I try to run my code.

Code: 
class Practice:
    def __init__(self, name, age, gender):
        self.Name = name
        self.Age = age
        self.Gender = gender

amount = 0
number = 97
person = ""

print("test")

a = Practice("Jasper", "17", "Male")
amount += 1
b = Practice("Xin Hao", "6", "Female")
amount += 1
c = Practice("Martijn", "83", "Male")
amount += 1
d = Practice("Sam", "34", "Female")
amount += 1
e = Practice("Maurice", "13624", "Male")
amount += 1

for one in range(0, amount):
    person = chr(number)
    for two in range(0, len(person.Name)):
        print(person.Name[two])
    number += 1
 
Error:
test Traceback (most recent call last): File "C:/Users/jaspe/PycharmProjects/untitled/Class Practice.py", line 26, in <module> for two in range(0, len(person.Name)): AttributeError: 'str' object has no attribute 'Name'
When I replace "person.Name" with "a.Name" the code works fine. Is it just that Python cannot read classes when their name gets imported from a variable?

Thank you in advance,

Jasper
Well, person is a string. You set it to a string with this line:

person = chr(number)
As the return value of the chr function is a string. If you want it to be an instance of the Practice class, you need to assign it as one like you did with a, b, c, d, and e.
I tried using a dictionary instead and this worked! Thanks a lot!