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 Instant Objects __init__

Sanjay Devadkar
PLUS
Sanjay Devadkar
Courses Plus Student 1,016 Points

I'd like to be able to set the name attribute at the same time that I create an instance. Can you add the code for doing

How to solve below challenge and please explain me **kwargs and also for key, vlaue stuff in the function I'd like to be able to set the name attribute at the same time that I create an instance. Can you add the code for doing that? Remember, you'll need to override the init method.

first_class.py
class Student:
    name = "Your Name"

    def __init__(self):
        name = self.name

    def praise(self):
        return "You inspire me, {}".format(self.name)

    def reassurance(self):
        return "Chin up, {}. You'll get it next time!".format(self.name)

    def feedback(self, grade):
        if grade > 50:
            return self.praise()
        return self.reassurance()

2 Answers

Ray Karyshyn
Ray Karyshyn
13,443 Points

Hi Sanjay,

You have successfully overridden the init method, but not correctly.

First off, you need to add a name argument to __init__:

def __init__(self, name):

Second, the order of the code inside the method is reversed, it should be -> where_you_want_to_be_stored = what_you_want_stored

def __init__(self, name):
    self.name = name

Now for **kwargs...

**kwargs allows you to pass keyworded variables as arguments to a function. (**kwargs is just a convention, you could write it with anything proceeding two asterisks (**))

For example:

def myFunction(**kwargs):
    for key, value in kwargs.items():
        print(key + " = " + value)


myFunction(name = "Sanjay") #  prints "name = Sanjay"

import random

class Dice(object):

def init(self, *args, **kwargs): self.name = kwargs.get('name', 'no_name') self.sides = [1,2,3,4,5,6]

def roll(self): return random.choice(self.sides)

d = Dice(name='first_dice')

print(d.roll())