Posted on • Originally published atdjangotricks.com on
Equivalents in Python and JavaScript. Part 4
In thelast three parts of the series of articles about analogies inPython andJavaScript, we explored lots of interesting concepts like serializing to JSON, error handling, using regular expressions, string interpolation, generators, lambdas, and many more. This time we will delve into function arguments, creating classes, using class inheritance, and defining getters and setters of class properties.
Function arguments
Python is very flexible with argument handling for functions: you can set default values there, allow a flexible amount of positional or keyword arguments (*args
and**kwargs
). When you pass values to a function, you can define by name to which argument that value should be assigned. All that in a way is now possible inJavaScript too.
Default values for function arguments inPython can be defined like this:
frompprintimportpprintdefreport(post_id,reason='not-relevant'):pprint({'post_id':post_id,'reason':reason})report(42)report(post_id=24,reason='spam')
InJavaScript that can be achieved similarly:
functionreport(post_id,reason='not-relevant'){console.log({post_id:post_id,reason:reason});}report(42);report(post_id=24,reason='spam');
Positional arguments inPython can be accepted using the*
operator like this:
frompprintimportpprintdefadd_tags(post_id,*tags):pprint({'post_id':post_id,'tags':tags})add_tags(42,'python','javascript','django')
InJavaScript positional arguments can be accepted using the...
operator:
functionadd_tags(post_id,...tags){console.log({post_id:post_id,tags:tags});}add_tags(42,'python','javascript','django');
Keyword arguments are often used inPython when you want to allow a flexible amount of options:
frompprintimportpprintdefcreate_post(**options):pprint(options)create_post(title='Hello, World!',content='This is our first post.',is_published=True,)create_post(title='Hello again!',content='This is our second post.',)
A common practice to pass multiple optional arguments to aJavaScript function is through a dictionary object, for example,options
.
functioncreate_post(options){console.log(options);}create_post({'title':'Hello, World!','content':'This is our first post.','is_published':true});create_post({'title':'Hello again!','content':'This is our second post.'});
Classes and inheritance
Python is an object-oriented language. Since ECMAScript 6 standard support, it's also possible to write object-oriented code inJavaScript without hacks and weird prototype syntax.
InPython you would create a class with the constructor and a method to represent its instances textually like this:
classPost(object):def__init__(self,id,title):self.id=idself.title=titledef__str__(self):returnself.titlepost=Post(42,'Hello, World!')isinstance(post,Post)==Trueprint(post)# Hello, World!
InJavaScript to create a class with the constructor and a method to represent its instances textually, you would write:
classPost{constructor(id,title){this.id=id;this.title=title;}toString(){returnthis.title;}}post=newPost(42,'Hello, World!');postinstanceofPost===true;console.log(post.toString());// Hello, World!
Now we can create two classesArticle
andLink
inPython that will extend thePost
class. Here you can also see how we are usingsuper
to call methods from the basePost
class.
classArticle(Post):def__init__(self,id,title,content):super(Article,self).__init__(id,title)self.content=contentclassLink(Post):def__init__(self,id,title,url):super(Link,self).__init__(id,title)self.url=urldef__str__(self):return'{} ({})'.format(super(Link,self).__str__(),self.url,)article=Article(1,'Hello, World!','This is my first article.')link=Link(2,'DjangoTricks','https://djangotricks.blogspot.com')isinstance(article,Post)==Trueisinstance(link,Post)==Trueprint(link)# DjangoTricks (https://djangotricks.blogspot.com)
InJavaScript the same is also doable by the following code:
classArticleextendsPost{constructor(id,title,content){super(id,title);this.content=content;}}classLinkextendsPost{constructor(id,title,url){super(id,title);this.url=url;}toString(){returnsuper.toString()+' ('+this.url+')';}}article=newArticle(1,'Hello, World!','This is my first article.');link=newLink(2,'DjangoTricks','https://djangotricks.blogspot.com');articleinstanceofPost===true;linkinstanceofPost===true;console.log(link.toString());// DjangoTricks (https://djangotricks.blogspot.com)
Class properties: getters and setters
In object oriented programming, classes can have attributes, methods, and properties. Properties are a mixture of attributes and methods. You deal with them as attributes, but in the background they call special getter and setter methods to process data somehow before setting or returning to the caller.
The basic wireframe for getters and setters of theslug
property inPython would be like this:
classPost(object):def__init__(self,id,title):self.id=idself.title=titleself._slug=''@propertydefslug(self):returnself._slug@slug.setterdefslug(self,value):self._slug=valuepost=newPost(1,'Hello, World!')post.slug='hello-world'print(post.slug)
InJavaScript getters and setters for theslug
property can be defined as:
classPost{constructor(id,title){this.id=id;this.title=title;this._slug='';}setslug(value){this._slug=value;}getslug(){returnthis._slug;}}post=newPost(1,'Hello, World!');post.slug='hello-world';console.log(post.slug);
The Takeaways
- In both languages, you can define default argument values for functions.
- In both languages, you can pass a flexible amount of positional or keyword arguments for functions.
- In both languages, object-oriented programming is possible.
As you might have noticed, I am offering a cheat sheet with the full list of equivalents inPython andJavaScript that you saw here described. At least for me, it is much more convenient to have some printed sheet of paper with valuable information next to my laptop, rather than switching among windows or tabs and scrolling to get the right piece of snippet. So I encourage you to get this cheat sheet and improve your programming!
Get the Ultimate Cheat Sheet of
Equivalents in Python and JavaScript
✨✨✨
Use it for good!
Top comments(1)

- LocationBerlin, Germany
- EducationVilnius University, Lithuania
- WorkFounder at "1st things 1st"
- Joined
For further actions, you may consider blocking this person and/orreporting abuse