Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Classes in PYTHON vs JAVASCRIPT

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    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 return
undefined

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

>Solution :

You need to declare it static, otherwise it’s an instance property:

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

In Python variables declared outside methods are static (no static keyword is needed).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading