Skip to main content
 首页 » 编程设计

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

2025年05月04日34yjmyzz

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