Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Object-Oriented Python (retired) Objects __init__

Dave Edwards
Dave Edwards
3,861 Points

No attribute being found if nothing entered when initiating a class

Hi guys,

I have the following code:

class Student:
    def __init__ (self, **kwargs):
        self.name = kwargs.get('name', 'Dave')
        self.age = kwargs.get('age', 18)
        self.lesson = kwargs.get('lesson', 'NONE')


    def register (self):
        print ("Hi {}".format(self.name))
        print ("\nYou are {} years old and studying {}".format(self.age, self.lesson))

when I run:

bob=Student

Then run:

bob.name

I get the following attribute error:

AttributeError: type object 'Student' has no attribute 'name'

However, if I create an instance of Student and explicitly put in a name value all is fine. It seems to be an issue with the defaults in the get method on kwargs.

Douglas North
Douglas North
10,884 Points

just add empty parenthesis: bob=Student()

Dave Edwards
Dave Edwards
3,861 Points

Well that was blidingly simple, thanks a lot. I had been focusing on the wrong area!

1 Answer