Python 类实现的 JavaScript 挂件是什么样的?

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

我正在研究这两种语言之间的区别,我想知道为什么我无法在不启动实例的情况下访问 javascript 类中的变量,但我可以在 python 中做到这一点

这是我们正在讨论的一个例子:

Python 类

    class Car: 
       all =[]
       def __init__(self, name):
          self.name = name

          Car.all.append(self)

       def get_car_name(self):
          return self.name
 
        
        
    bmw = Car("BMW")
    mercedez = Car("MERCEDEZ")

    print(Car.all)

运行此代码会返回所有汽车的列表(这是我创建的实例) [<main.汽车对象位于0x0000022D667664E0>,<main.汽车对象位于0x0000022D66766510>]

JAVASCRIPT类

    class Car {
      all = [];
      constructor(name, miles) {
      this.name = name;
      this.miles = miles;

      this.all.push(this);
      }
     }

    let ford = new Car("ford", 324);
    let tesla = new Car("tesla", 3433);

    console.log(Car.all);

如果我使用此代码,console.log 将返回 未定义

在javascript中,如果我想获得所有的值,我必须使用这样的实例

console.log(ford.all);

这将仅返回创建的 ford 实例

[ Car { all: [Circular *1], name: 'ford', miles: 324 } ]

但是在Python中,如果我打印出一个实例,它会返回this

print(bmw.all)

[<__main__.Car object at 0x00000199CAF764E0>, <__main__.Car object at 0x00000199CAF76510>]

即使我调用了一个实例的全部,它也会返回创建的两个实例

javascript python class
2个回答
3
投票

你需要声明它是静态的,否则它是一个实例属性:

class Car {
  static all = [];
  constructor(name, miles) {
  this.name = name;
  this.miles = miles;

  Car.all.push(this);
  }
 }

let ford = new Car("ford", 324);
let tesla = new Car("tesla", 3433);

console.log(Car.all);

在 Python 中,在方法外部声明的变量是静态的(不需要

static
关键字)。


0
投票

all
汽车数组甚至可以,或者更确切地说应该,作为一个私有静态字段实现,并带有受控静态
all
吸气剂作为其对应物。

人们不希望有一个可以直接公开访问的

Car.all
,因为每个人都有能力操作这个数组。静态
all
getter 允许例如将
all
cars 数组的浅拷贝作为返回值,因此除了构造函数之外没有其他进程推入该数组,并且只有静态
all
getter 是第二个进程确实控制
all
数据如何向公众公开。

class Car {
  // - note the hash prefix ... private static .
  static #all = [];

  constructor(name, miles) {

    Object.assign(this, { name, miles });

    // - push into the private static array.
    Car.#all.push(this);
  }
  // - implement a controlled static getter.
  static get all() {

    // - never ever allow direct access to
    //   a private/protected instance.

    // - return e.g. a shallow copy of the
    //   private static `all` (cars) array.
    return [...Car.#all];
  }
 }

let ford = new Car("ford", 324);
let tesla = new Car("tesla", 3433);

console.log(Car.all);
.as-console-wrapper { min-height: 100%!important; top: 0; }

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