0

I'm getting the error "AttributeError: 'NoneType' object has no attribute 'name'" for the code below:

class Student:
    def __init__(self, name, house):
        if not name:
            raise ValueError("Missing name!")
        self.name = name
        self.house = house

def main():
    student = get_student()
    print(f"{student.name} from {student.house}")


def get_student():
    name = input("Name: ")
    house = input("House: ")
    try:
        return Student(name, house)
    except ValueError:
        print("Please make sure to enter a name...")
        main()


if __name__ == "__main__":
    main()

I was hoping that the main() call inside get_student() function will create a recursion-like effect and will allow the program to go on until both 'name' and 'house' have been inserted. However, what happens is a little different.

When I enter name and house, the program works. When I omit entering a name, it does print the ValueError message in get_student() and prompts for another set of inputs.. but, then I get "AttributeError: 'NoneType' object has no attribute 'name'".

Am I doing something completely stupid? Any help is much appreciated.

1 Answers1

0

Adding the error message is always helpful.

I assume that your AttributeError also mentions that you have a NoneType object? If so, when you do not provide a name and raise a ValueError within Student, your Student object dissolves into a None.

The issue comes when you are call the menu function recursively. The student variable with the None value has not printed at this point. The program is waiting for the user to input a valid name and a house.

Once that valid name and house are place, the Student object will be initialized appropriately, and its attributes printed. Your program will then move down the call stack, and print the None value from the Student object that originally raised the ValueError.

Rather than entering a recursive call to main, you can add a while loop with an exit condition. The exit condition would be a non-empty string for the variable name

awakenedhaki
  • 186
  • 5
  • Thank you for the reply! Sorry I forgot the error message. And yes: it is 'NoneType' object related. I'll update the question. Problem solving-wise, I know that a while loop is an easier method, but I was wondering about why isn't the 'student' variable getting replaced during the recursive call to the main() function. The fourth para of your answer does explain part of it with regard to call stack, but I'm still confused about why won't the student variable get overwritten during the next call, and instead move to the print statement of main function. – Tharindu Dissanayake Jun 14 '23 at 00:36