0

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.

  • @MartijnPieters that's not a good super target, the OP is asking the opposite, in fact, how to get objects to share class data! – juanpa.arrivillaga Sep 15 '17 at 22:41
  • To answer your question, `year` is still static, however, when you do `car1.year = "1995"` you *shadow the class variable with an instance variable*. Assignment is not mutation. – juanpa.arrivillaga Sep 15 '17 at 22:43
  • @juanpa.arrivillaga right, but this is still about the difference between calling methods on a mutable class attribute vs assigning to an instance attribute. Have a better dupe? – Martijn Pieters Sep 15 '17 at 22:56
  • @juanpa.arrivillaga the different answers on that post do address the concepts that apply here too. – Martijn Pieters Sep 15 '17 at 22:57
  • Make sure to check out [this answer in the targeted duplicate](https://stackoverflow.com/questions/15790493/python-changing-class-variables) – juanpa.arrivillaga Sep 15 '17 at 23:04
  • @MartijnPieters, Thanks guys! I need to learn concepts about mutation in Python. I'm so excited to learn new things about Python. It just feels weird when transform from Java to Python. – Patrick Yu Sep 16 '17 at 00:15

0 Answers0