Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Classes error
#1
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
Reply
#2
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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
I tried using a dictionary instead and this worked! Thanks a lot!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  classes , error at line 88 name finnKategori not defined sydlender 3 2,938 Nov-12-2018, 09:08 PM
Last Post: buran
  Using classes? Can I just use classes to structure code? muteboy 5 5,061 Nov-01-2017, 04:20 PM
Last Post: metulburr

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020