Equivalents in Python and JavaScript. Part 4
Tags: advanced, intermediate, javascript, python
Published: 2018-07-09 10:58:03

---
title: Equivalents in Python and JavaScript. Part 4
published: true
tags: Advanced,Intermediate,JavaScript,Python
canonical_url: http://djangotricks.blogspot.com/2018/07/equivalents-in-python-and-javascript-part-4.html
series: Equivalents in Python and JavaScript
---

 ![](https://3.bp.blogspot.com/-IUXEO64Y6q8/WzrC947Je8I/AAAAAAAAB58/KyzGfiel_6AxNOHLu4lHsZhTPyznTvmfQCLcBGAs/s1600/equivalents-in-python-and-javascript-part-4.png) 

In the [last](https://dev.to/djangotricks/equivalents-in-python-and-javascript-part-3-4icc) three parts of the series of articles about analogies in __Python__ and __JavaScript__, 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 in __JavaScript__ too.

Default values for function arguments in __Python__ can be defined like this:

```python
from pprint import pprint

def report(post_id, reason='not-relevant'):
    pprint({'post_id': post_id, 'reason': reason})
    
report(42)
report(post_id=24, reason='spam')
```

In __JavaScript__ that can be achieved similarly:

```javascript
function report(post_id, reason='not-relevant') {
    console.log({post_id: post_id, reason: reason});
}

report(42);
report(post_id=24, reason='spam');
```

---

Positional arguments in __Python__ can be accepted using the `*` operator like this:

```python
from pprint import pprint

def add_tags(post_id, *tags):
    pprint({'post_id': post_id, 'tags': tags})
    
add_tags(42, 'python', 'javascript', 'django')
```

In __JavaScript__ positional arguments can be accepted using the `...` operator:

```javascript
function add_tags(post_id, ...tags) {
    console.log({post_id: post_id, tags: tags});
}

add_tags(42, 'python', 'javascript', 'django');    
```

---

Keyword arguments are often used in __Python__ when you want to allow a flexible amount of options:

```python
from pprint import pprint

def create_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 a __JavaScript__ function is through a dictionary object, for example, `options`.

```javascript
function create_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 in __JavaScript__ without hacks and weird prototype syntax.

In __Python__ you would create a class with the constructor and a method to represent its instances textually like this:

```python
class Post(object):
    def __init__(self, id, title):
        self.id = id
        self.title = title
        
    def __str__(self):
        return self.title

post = Post(42, 'Hello, World!')
isinstance(post, Post) == True
print(post)  # Hello, World!
```

In __JavaScript__ to create a class with the constructor and a method to represent its instances textually, you would write:

```javascript
class Post {
    constructor (id, title) {
        this.id = id;
        this.title = title;
    }
    toString() {
        return this.title;
    }
}

post = new Post(42, 'Hello, World!');
post instanceof Post === true;
console.log(post.toString());  // Hello, World!
```

---

Now we can create two classes `Article` and `Link` in __Python__ that will extend the `Post` class. Here you can also see how we are using `super` to call methods from the base `Post` class.

```python
class Article(Post):
    def __init__(self, id, title, content):
        super(Article, self).__init__(id, title)
        self.content = content

class Link(Post):
    def __init__(self, id, title, url):
        super(Link, self).__init__(id, title)
        self.url = url
        
    def __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) == True
isinstance(link, Post) == True
print(link)
# DjangoTricks (https://djangotricks.blogspot.com)
```

In __JavaScript__ the same is also doable by the following code:

```javascript
class Article extends Post {
    constructor (id, title, content) {
        super(id, title);
        this.content = content;
    }
}

class Link extends Post {
    constructor (id, title, url) {
        super(id, title);
        this.url = url;
    }
    toString() {
        return super.toString() + ' (' + this.url + ')';
    }
}

article = new Article(1, 'Hello, World!', 'This is my first article.');
link = new Link(2, 'DjangoTricks', 'https://djangotricks.blogspot.com');
article instanceof Post === true;
link instanceof Post === 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 the `slug` property in __Python__ would be like this:

```python
class Post(object):
    def __init__(self, id, title):
        self.id = id
        self.title = title
        self._slug = ''
        
    @property
    def slug(self):
        return self._slug
        
    @slug.setter
    def slug(self, value):
    	self._slug = value
    	    
post = new Post(1, 'Hello, World!')
post.slug = 'hello-world'
print(post.slug)
```

In __JavaScript__ getters and setters for the `slug` property can be defined as:

```javascript
class Post {
    constructor (id, title) {
        this.id = id;
        this.title = title;
        this._slug = '';
    }
    
    set slug(value) {
        this._slug = value;
    }
    
    get slug() {
        return this._slug;
    }
}

post = new Post(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 in __Python__ and __JavaScript__ 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!

<center><a href="https://www.djangotricks.com/goodies/YbnpiLKBmAZi/" target="_blank">✨✨✨<br />Get the Ultimate Cheat Sheet of<br />Equivalents in Python and JavaScript<br />✨✨✨</a></center>

Use it for good!