Analogs in Python and JavaScript. Part four

Original author: Aidas Bendoraitis aka archatas
  • Transfer

The fourth part of a series of articles about analogues in Python and JavaScript.


In this part: the arguments of functions, the creation and work with classes, inheritance, getters-setters and class properties.


Summary of the previous parts:


  1. Part one : type conversion, ternary operator, property access by property name, dictionaries, lists, strings, string concatenation.
  2. Part Two : JSON, regulars, errors, exceptions
  3. Part three : modern Python and JS: string patterns (f-strings), list unpacking, lambda functions, list iterations, generators, sets.

Function arguments


In Python a comprehensive toolkit for working with function arguments - there is a default value, a variable number of positional and keyword arguments ( *argsand **kwargs).


When you pass a value to a function, you can specify the name of the argument to which this value will be passed. JS also has this feature.


Default values ​​for function arguments can be defined in Python:


from pprint import pprint
defreport(post_id, reason='not-relevant'):
    pprint({'post_id': post_id, 'reason': reason})
report(42)
report(post_id=24, reason='spam')

In JS, 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 in Python can be processed using the operator *:


from pprint import pprint
defadd_tags(post_id, *tags):
    pprint({'post_id': post_id, 'tags': tags})
add_tags(42, 'python', 'javascript', 'django')

In JS, positional arguments are processed using the operator ...:


functionadd_tags(post_id, ...tags) {
    console.log({post_id: post_id, tags: tags});
}
add_tags(42, 'python', 'javascript', 'django');    

Named arguments are often used in Python when it is necessary to pass a variable number of arguments:


from pprint import pprint
defcreate_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.',
)

Passing a set of named arguments to JS is implemented using a dictionary ( optionsin this example):


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. JS since ECMAScript 6 also allows you to write object-oriented code without any tricks and syntactic turns.


Python. Create a class, constructor and method for the text representation of the object:


classPost(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!

Similar actions on JS:


classPost{
    constructor (id, title) {
        this.id = id;
        this.title = title;
    }
    toString() {
        returnthis.title;
    }
}
post = new Post(42, 'Hello, World!');
post instanceof Post === true;
console.log(post.toString());  // Hello, World!

Let's create two classes Articleand LinkPython, which are inherited from the class Post. You may notice that we use the function superto access the methods of the base class Post:


classArticle(Post):def__init__(self, id, title, content):
        super(Article, self).__init__(id, title)
        self.content = content
classLink(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)

The same in JS:


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 = 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 have attributes, methods, and properties. Properties are a mixture of attributes and methods. You can treat properties as attributes, but somewhere inside they call special methods called getters and setters for specific data processing.
In this example, Python shows a basic way of describing a getter and setter for a property slugusing decorators:


classPost(object):def__init__(self, id, title):
        self.id = id
        self.title = title
        self._slug = ''    @propertydefslug(self):return self._slug
    @slug.setterdefslug(self, value):
        self._slug = value
post = Post(1, 'Hello, World!')
post.slug = 'hello-world'
print(post.slug)

In JS, the getter and setter for a property slugcan be described as:


classPost{
    constructor (id, title) {
        this.id = id;
        this.title = title;
        this._slug = '';
    }
    set slug(value) {
        this._slug = value;
    }
    get slug() {
        returnthis._slug;
    }
}
post = new Post(1, 'Hello, World!');
post.slug = 'hello-world';
console.log(post.slug);

findings


  • In both languages, the default values ​​of the function arguments can be described.
  • In both languages, an arbitrary number of named or positional arguments can be passed to the function.
  • Both languages ​​support an object-oriented programming paradigm.

Well, and finally, the author of the original post proposes to buy from him a pdf with colored cheat sheets on python and javascript for fifteen bucks .


Print and hang on the wall or make a paper airplane - you decide!


Also popular now: