Javascript `this` vs Python `self` Constructors

Question:

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?

Asked By: Vincent Tang

||

Answers:

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):
        return self.views += 1

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:
         return self.views += 1 
Answered By: modesitt

There was some errors on the python solution fixed it now

#Constructors
class Course:

    def __init__(self,title,instructor,level,published,views):

        self.propTitle = title
        self.propInstructor = instructor
        self.propLevel = level
        self.propPublished = published
        self.propViews = views

    def update_views(self):
        self.propViews += 1
        return self.propViews

# Create objects
courseA = Course("A title", "A instructor", 1, True, 0)
courseB = Course("B title", "B instructor", 1, True, 123456)

# Print object property and use object method
print(courseA.propTitle)
print(courseB.update_views())

Result print out

A title

123457

Using print(courseB.update_views) outputs this though,<bound method Course.update_views of <__main__.Course object at 0x7f9f79978908>> , use print(courseB.update_views())

Answered By: Vincent Tang