📜 ⬆️ ⬇️

Analogs in Python and JavaScript. Part four

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


Python has extensive tools for working with function arguments - there are default values, a variable number of positional and named arguments ( *args and **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 def report(post_id, reason='not-relevant'): pprint({'post_id': post_id, 'reason': reason}) report(42) report(post_id=24, reason='spam') 

In JS, similarly:


 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 processed using the * operator:


 from pprint import pprint def add_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:


 function add_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 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.', ) 

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


 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. 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:


 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! 

Similar actions on JS:


 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! 

Create two classes, Article and Link in Python, which will be inherited from the Post class. You may notice that we use the super function to access methods of the Post base class:


 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) 

The same in JS:


 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 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 the slug property using decorators:


 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 = Post(1, 'Hello, World!') post.slug = 'hello-world' print(post.slug) 

In JS, the getter and setter for the slug property can be described as:


 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); 

findings



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


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


')

Source: https://habr.com/ru/post/419271/


All Articles