gpt4 book ai didi

Javascript `this` 与 Python `self` 构造函数

转载 作者:太空宇宙 更新时间:2023-11-04 08:40:06 26 4
gpt4 key购买 nike

Javascript 构造函数 + 创建对象示例

//Constructor
function Course(title,instructor,level,published,views){
this.title = title;
this.instructor = instructor;
this.level = level;
this.published = published;
this.views = views;
this.updateViews = function() {
return ++this.views;
}
}

//Create Objects
var a = new Course("A title", "A instructor", 1, true, 0);
var b = new Course("B title", "B instructor", 1, true, 123456);

//Log out objects properties and methods
console.log(a.title); // "A Title"
console.log(b.updateViews()); // "123457"

Python 的对应项是什么? (构造函数/或类 + 创建对象实例 + 注销属性和方法?)

Python 的 self 和 Javascript 的 this 有区别吗?

最佳答案

这是一个 python 翻译:

class Course:

def __init__(self,title,instructor,level,published,views):
self.title = title
self.instructor = instructor
self.level = level
self.published = published
self.views = views

def update_views(self):
return self.views += 1

您必须声明一个类,然后初始化该类的一个实例,如下所示:

course = Course("title","instructor","level","published",0)

一些显着的区别是 self 不是隐式可用的,但实际上是该类所有方法的必需参数。但是,你应该咨询 the documentation 有关 python 类的更多信息。

编辑

截至python3.7 ,我觉得有义务表明新推出的 dataclasses是另一种(并且越来越普遍)编写像这样的简单类的方法。

from dataclasses import dataclass

@dataclass
class Course:

title: str
instructor: str
level: str
published: bool
views: int

def update_views(self) -> int:
return self.views += 1

关于Javascript `this` 与 Python `self` 构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45575179/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com