Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23247

How does the JavaScript pendant of a Python class implementation look like?

$
0
0

Am studying the difference between those two languages and i was wondering why i can't access the variables in javascript classes without initiating an instance but i can do that in python

here is an example of what am talking about:

PYTHON CLASS

    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)

Running this code returns a list of all cars (which are the instance that i have created)[<main.Car object at 0x0000022D667664E0>, <main.Car object at 0x0000022D66766510>]

JAVASCRIPT Class

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

if i used this code the console.log will returnundefined

in javascript if i want to get the value of all i have to use an instance like this

console.log(ford.all);

this will return only the instance of ford that was created[ Car { all: [Circular *1], name: 'ford', miles: 324 } ]

but otherwise in python this if i printed out an instance all it will return this

print(bmw.all)

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

it returns the two instance that is created even if i called the all of one instance


Viewing all articles
Browse latest Browse all 23247

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>