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 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
2
Answers
You need to declare it static, otherwise it’s an instance property:
In Python variables declared outside methods are static (no
static
keyword is needed).The
all
cars array even can be, or rather should be, implemented as a private static field with a controlled staticall
getter as its counterpart.One does not want to have a directly public accessible
Car.all
since everyone is capable of manipulating this array. The staticall
getter allows for instance a shallow copy of theall
cars array to be the return value, thus no other process than the constructor pushes into this array, and just the staticall
getter is the 2nd process which does control how theall
data is exposed into public.