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

问题描述 投票:0回答:2

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
有区别吗?

javascript python object constructor
2个回答
11
投票

这是一个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):
        self.views += 1
        return self.views

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

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

一些显着的差异是

self
不是隐式可用的,但实际上是该类的所有方法的必需参数。但是,您应该查阅 有关 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:
         self.views += 1
         return self.views

1
投票

python 解决方案存在一些错误,现已修复

#Constructors
class Course:

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

        self.propTitle = title
        self.propInstructor = instructor
        self.propLevel = level
        self.propPublished = published
        self.propViews = views

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

# Create objects
courseA = Course("A title", "A instructor", 1, True, 0)
courseB = Course("B title", "B instructor", 1, True, 123456)

# Print object property and use object method
print(courseA.propTitle)
print(courseB.update_views())

结果打印

一个标题

123457

使用

print(courseB.update_views)
会输出这个,
<bound method Course.update_views of <__main__.Course object at 0x7f9f79978908>>
,使用
print(courseB.update_views())

© www.soinside.com 2019 - 2024. All rights reserved.