Search code examples
javascriptpythonobjectconstructor

Javascript `this` vs Python `self` Constructors


Javascript Constructor + create objects example

//Constructor
function Course(title,instructor,level,published,views){
    this.title = title;
    this.instructor = instructor;
    this.level = level;
    this.published = published;
    this.views = views;
    this.updateViews = function() {
        return ++this.views;
    }
}

//Create Objects
var a = new Course("A title", "A instructor", 1, true, 0);
var b = new Course("B title", "B instructor", 1, true, 123456);

//Log out objects properties and methods
console.log(a.title);  // "A Title"
console.log(b.updateViews()); // "123457"

what is the python equivalent of this? (Constructor function / or class + create object instances + log out properties & methods?)

Is there a difference between self from python and this from Javascript?


Solution

  • Here is a python translation:

    class Course:
        def __init__(self, title, instructor, level, published, views):
            self.title = title
            self.instructor = instructor
            self.level = level
            self.published = published
            self.views = views
    
        def update_views(self):
            self.views += 1
            return self.views
    

    You must declare a class, then initialize an instance of that class as follows:

    course = Course("title","instructor","level","published",0)
    

    Some notable differences are that self is not implicitly available but is actually a required parameter to all methods of the class. However, you should consult the documentation on python classes for more information.

    Edit

    As of python3.7, I feel obligated to show that newly introduced dataclasses are another (and increasingly common) way of writing simple classes like this.

    from dataclasses import dataclass
    
    @dataclass
    class Course:
         title: str 
         instructor: str 
         level: str 
         published: bool
         views: int 
    
         def update_views(self) -> int:
             self.views += 1
             return self.views