Hacker News new | ask | show | jobs
by DeepDuh 5031 days ago
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.
1 comments

> 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?