Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Django Basics Model Administration Adding Instances

Sahar Nasiri
Sahar Nasiri
7,454 Points

There is no constructor

We have not write any init function for our Course class, how come we can pass values to our attributes while we are building an instance of the Course class?

>>> Course(title="Python Collections", description="Learn about list, dict and tuple").save()  

2 Answers

Kristian Gausel
Kristian Gausel
14,661 Points

Because in django it is probably written using **keywordargs. So it just takes the keywords you specify and add them.

you can write your own constructor like this in a way close to this:

class Example(object):
    def __init__(self, *args, **kwargs):
        self.data = kwargs
Anthony Albertorio
Anthony Albertorio
22,587 Points

Remember that we are inheriting from the models.Model class. So those functions should be there.

According to "yak" on Stack Overflow: "In a single inheritance case (when you subclass one class only), your new class inherits methods of the base class. This includes init. So if you don't define it in your class, you will get the one from the base...."

See: https://stackoverflow.com/questions/10482953/python-extending-with-using-super-python-3-vs-python-2

Also see the docs for models.Model Notice it takes in **kwargs. see: https://docs.djangoproject.com/en/2.0/ref/models/instances/#django.db.models.Model

Hope this helps