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 trialHank de Roover
1,578 Points__init__
Override init in Student so name can be set when an instance is created with name="some name". You might want to unpack a dict.
can't figure out this one step help would be appreciated.
2 Answers
Kevin Lozandier
Courses Plus Student 53,747 PointsHi, Hank de Roover:
In Python, you must unpack a dictionary to be able to access its values efficiently. You must also pass into self, because __init__
is something you want to be run on an instance of the class. In methods, the naming convention in languages that require dictionaries to be unpacked to be efficiently accessed is kwargs
You then use kwargs.get
(or whatever name you decided to use for the variable containing the result of unpacking the dictionary) to get the value for a particular key with an optional second parameter to have an alternate value obtained if a particular key couldn't be found within the unpacked dictionary.
For example the following code snippet will obtain the value associated with key foo
in an unpacked dictionary kwargs; if it doesn't exist, baz
is returned:
self.bar = kwargs.get("foo", "baz")
The use of self
in the previous code example may have been strange to you.
In Python, to declare instance methods concisely, you pass in self
as the first parameter. This is needed to actually use self
to explicitly set, modify, and del properties of a particular instance.
Here's a snippet of the advice of both.:
class Student:
def __init__(self, **kwargs):
self.name = kwargs.get("name", "some name")
stuartholland
10,773 PointsTo help with understanding the question, we're overriding init because it is by default part of any class created. By defining it we are by definition, overriding the default init.
Hank de Roover
1,578 PointsHank de Roover
1,578 PointsThanks man that definitely helped have a good day!