0

I have an example class:

class A():
  x = 10
  y = 10
  
  @classmethod
  def add_to_y(cls):
    cls.y += 1
    
    
    
first, second = A(), A()

print(first.x, second.x)
A.x +=1
print(first.x, second.x)
second.add_to_y()
print(first.y, second.y)

Which returns:

10 10
11 11
11 11

Both ways increment class variable x or y. Is there a difference? Which one is the recommended way of incrementing a class variable?

Trying to understand when should I use one instead of the other, and I just think that using classmethod is kind of convenient to using inside methods that might do more than just one thing, or am I missing something?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Jonas Palačionis
  • 4,591
  • 4
  • 22
  • 55
  • 3
    `Class.x += 1` always updates that specific class, whereas `instance.add_to_y()` updates whichever is the _current_ `cls`; where inheritance is involved you may want one or the other. – jonrsharpe May 03 '22 at 15:24
  • Is inheritance the only difference between the two ways? – Jonas Palačionis May 03 '22 at 15:25
  • 1
    I would use the classmethod, because you can give it a meaningful name that explains _why_ you are adding to the variable, such as `level_up()` or `purchase_new_car()`. – John Gordon May 03 '22 at 15:32
  • 1
    In my view, using the Class. fits with the "Explicit is better than implicit" line from "The Zen of Python". In using instances, or even methods on instances, there is always the potential the class variable could be shadowed by an instance variable. Also, to people looking at your code for the first time, MyClass.variable = 10 is much less likely to be misunderstood than my_instance.set_variable(10). – John Carter May 03 '22 at 15:35
  • 1
    Arguably, it may be bad form / confusing / unnecessary to call a class method from an instance https://stackoverflow.com/questions/692040/is-it-bad-form-to-call-a-classmethod-as-a-method-from-an-instance. It's certainly confusing in this case because it looks like you're altering an instance variable rather than a class variable. If necessary to do this for inheritance reasons I would consider it labelling something like `add_to_class_y` to make this explicit. – Stuart May 03 '22 at 15:36
  • Thank you for comments, the combination of your comments answers my question. – Jonas Palačionis May 03 '22 at 18:37

0 Answers0