I'm studying Python by myself. I learned Java and C# before. I'm a little confused about the class variables in Python. Here is my example:
class Car:
ownerList = []
year = "2000"
def __init__(self, m, c):
self.make = m
self.color = c
As I understand, "ownerList" is a list object, "year" is a class variable of the class "Car".
When I create two instances of Car and then append new elements into "ownerList", all Car instances will share the same list object. Here is what I meant:
car1 = Car("Honda", "Red")
car2 = Car("Toyota", "Black")
car1.ownerList.append("A")
car2.ownerList.append("B")
Car.ownerList.append("C")
car1.ownerList[0] = "D"
print(car1.ownerList)
print(car2.ownerList)
print(Car.ownerList)
The outputs are the same: ['D', 'B', 'C']
However, it is different when I try to change values of "year" variable:
car1.year = "1995"
print("Car.year = " + Car.year)
print("car1.year = " + car1.year)
print("car2.year = " + car2.year)
output: Car.year = 2000
car1.year = 1995
car2.year = 2000
As you can see, if I update "year" of car1, the "year" in Car class and car2 instance are not changed.
Then I tested on changing the "year" of class Car:
Car.year = "2017"
print("Car.year = " + Car.year)
print("car1.year = " + car1.year)
print("car2.year = " + car2.year)
output: Car.year = 2017
car1.year = 1995
car2.year = 2017
Here, "year" of car1 is not changed!
Why class variable is not static but list object is static??
Hope I stated my question clear for you to understand.