by std_throwaway · 8y ago · 0 comments
>>> class Foo:
... def bar(self):
... print('foo')
...
>>> class Baz:
... def bar(self):
... print('baz')
...
>>> f = Foo()
>>> f
<__main__.Foo object at 0x7fa311e7a278>
>>> f.bar()
foo
>>> f.__class__ = Baz
>>> f
<__main__.Baz object at 0x7fa311e7a278>
>>> f.bar()
bazIs this like an unsafe pointer cast where “you are responsible, and it will likely blow up spectacularly if you don’t know what you are doing” or is it something safer that will magically work e.g with types of different size?
- Does that work even if the types had fields? Yup!
- What about it the fields had a different total size? Totally fine!
- What if Baz had no parameterless constructor (I.e only had a contractor that guaranteed arg > 0 for example)? Then you throw an exception when you call the constructor.
- Is this like an unsafe pointer cast where “you are responsible, and it will likely blow up spectacularly if you don’t know what you are doing” or is it something safer that will magically work e.g with types of different size?
Mostly the former, but if you're coming from a strongly typed compiled language, it may feel like a bit of the latter too, since if you don't run into any obvious runtime incompatibilities, it'll all "just seem to work" even if the underlying classes are 200% different.
(Disclaimer, I've been using python for ~decade now but am still always nervous to speak authoritatively about it, since I work with peers who are FAR deeper in the actual implementation than I am, and I run the risk of being subtlety incorrect.)
I was assuming that doing
myobj.__class__ = whatever
Would not call any constructors?As with most things, there are trade-offs.
I wouldn't qualify this as an advantage; it encourages bad code and it precludes a lot of good tooling (including tooling which would automate the sort of refactoring you'd like to avoid).
That's a matter of opinion, not a fact. It can be thought of as a shortcut for an applied mixin, without the needless pollution and boilerplate.