Hacker News new | ask | show | jobs
by madsr 1476 days ago
I think this example is quite deceptive. When setting obj.a and obj.b, what is your intention? If you want to set the instance attributes, you should have created self.a and self.b in the class constructor.

  class A:
    a = (1,)
    b = [1,]
    def __init__(self):
      self.a = (1,)
      self.b = [1,]

  A.a # this is the class attribute
    (1,)
  A.b # class attribute
    [1]
  obj = A()
  obj.a # instance attribute
    (1,)
  obj.b
    [1]
  obj.a += (2,)
  obj.b += [2,]
  A.a 
    (1,) # still the same class attribute
  A.b
    [1]
  obj.a
    (1, 2) # instance attribute appended
  obj.b
    [1, 2]
1 comments

I think that's the point is that it does seem rather ambiguous as to the intent. If someone is new to programming entirely, what are they thinking is happening with an operation *on obj.a or obj.b? If they know other languages and are just starting out learning Python, what expectations are they bringing from those languages?

If I had had magic wand, I'd make operations on class attributes from an instance a syntax error, and only allow it from the class name, and perhaps with special syntax like in C++, e.g.:

    A::a = (1,)
    A::b = [1,]
*edit: operation on obj.a or obj.b...