Python Object-Oriented Python Instant Objects Your first class

Tinotenda Mangarai
Tinotenda Mangarai
3,093 Points

What is wrong with my code. Someone help please. Been stuck for too long

Challenge Task 2 of 2 make an instance of your class named me. Then print() out the name attribute. Its not working

first_class.py
class Student:
    name = "Tino"
    me = Student()
    print(me.name)
Jeff Muday
Jeff Muday
Treehouse Moderator 25,018 Points

You can fix your scenario with simple indentation changes. Python is very sensitive to indentation as it denotes the block level of code.

class Student:
    # here we are defining a class
    name = "Tino" # name is a PROPERTY of Student

# the next two statements are NOT indented because these are at the top level
me = Student() # here we "instantiate" me as a Student() class object
print(me.name) # here we access the PROPERTY name

2 Answers

Fred Gablick
Fred Gablick
2,434 Points

You're thinking of this as a function instead of an object class. You need to define the object outside of the class. This is quick and dirty, but I think you'll see it:

>>> class Student:
...     pass
... 
>>> me = Student()
>>> me.nickname = "Bonehead"
>>> print(me.nickname)
Bonehead

You can use an init function inside the class to define your attributes, but you still want to define the object outside of the class.

>>> class Student:
...     def __init__(self, name):
...             self.name = name
... 
>>> me = Student("Bonehead")
>>> print(me.name)
Bonehead
>>> 

I hope that helps.

Tinotenda Mangarai
Tinotenda Mangarai
3,093 Points

The problem was with indentation. Thank you all