Python和JavaScript中的类似物。 第四部分

有关Python和JavaScript类似物的系列文章的第四部分。


在这一部分中:函数参数,创建和使用类,继承,设置方法获取器和类属性。


先前部分的摘要:


  1. 第一部分 :类型转换,三元运算符,按属性名称访问属性,字典,列表,字符串,字符串连接。
  2. 第二部分 :JSON,常规,异常错误
  3. 第三部分 :现代Python和JS:字符串模式(f线),列表解压缩,lambda函数,列表迭代,生成器,集合。

功能参数


Python具有用于处理函数参数的广泛工具包-有默认值,可变数量的位置和命名参数( *args**kwargs )。


将值传递给函数时,可以指定该值将传递给的参数的名称。 JS也具有此功能。


函数参数的默认值可以在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') 

在JS中,类似地:


 function report(post_id, reason='not-relevant') { console.log({post_id: post_id, reason: reason}); } report(42); report(post_id=24, reason='spam'); 

可以使用*运算符处理Python中的位置参数:


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

在JS中,使用...运算符处理位置参数:


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

当您需要传递可变数量的参数时,命名参数通常在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.', ) 

使用字典来实现将一组命名参数传递给JS(此示例中的options ):


 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.' }); 

类和继承


Python是一种面向对象的语言。 从ECMAScript 6开始,JS还允许您编写没有任何技巧和语法的面向对象的代码。


巨蟒 我们为对象的文本表示形式创建一个类,构造函数和方法:


 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! 

对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! 

在Python中创建两个ArticleLink类,它们将从Post类继承。 您可能会注意到,我们使用super功能来访问Post基类的方法:


 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) 

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

类属性:getter和setter。


在面向对象的编程中,类具有属性,方法和属性。 属性是属性和方法的混合体。 您可以将属性视为属性,但是在它们内部的某些地方调用称为getters / setters的特殊方法以进行特定的数据处理。
在此示例中,Python显示了使用装饰器描述slug属性的getter和setter的基本方法:


 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) 

在JS中, slug属性的getter和setter可以描述为:


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

结论


  • 在这两种语言中,您都可以描述函数参数的默认值。
  • 在这两种语言中,您都可以将任意数量的命名或位置参数传递给函数。
  • 两种语言都支持面向对象的编程范例。

好吧,最后,原始帖子的作者提议以15美元的价格从他那里购买pdfku,带有彩色作弊表的python和javascript


打印并挂在墙上或制成纸飞机-由您决定!

Source: https://habr.com/ru/post/zh-CN419271/


All Articles