Hacker News new | ask | show | jobs
by masklinn 5031 days ago
> Not the one you replied to, but one thing that hits me as awkward is the default static behavior of variables.

There's no default anything, what you wrote sets "bar = 1" on the class itself, nothing more an nothing less, just as if you'd written:

    Foo = type("Foo", (object,), {'bar': 1})
(in fact that's pretty much what the class statement is sugar for)

If you want to set it on the instance, set it on the instance.

Python's class context is a namespace like every other, you can do any computation you wish in there, and at the end the ``class`` statements collects all bindings of the namespace and sets them on the class.

1 comments

Well in my case foo = Foo(); print foo.bar will print 1, so it does 'kinda' work as a default value. And that's ok, I just remembered there to be some case where it didn't behave the way I expected it to (e.g. instance member assignment overriding the content of another instance), but I wasn't able to reproduce it right now.
> Well in my case foo = Foo(); print foo.bar will print 1

Of course it will, Python's attribute-resolution (as do most languages) tries the instance, then the class, then the superclass, then... why wouldn't it work?

> I just remembered there to be some case where it didn't behave the way I expected it to (e.g. instance member assignment overriding the content of another instance)

Only two way I see for that to happen:

1. Re-setting the member on the class itself, not the instance

2. Or having the member be mutable and mutating it, since it's set on the class it's shared by all instances.

Right, of course it was the mutable use of an internal data structure.

  class Foo:
	bar = [1]

  foo1 = Foo()
  foo2 = Foo()
  foo2.bar.append(2)
  print foo1.bar
  print foo2.bar
prints [1, 2] [1, 2]

And that's the reason why I don't like that the standard way I define common instance members is an init function. Are there any decorators I could use to do that outside of any class function?