How do I extend a class that I never instantiate myself?
speeze.pearson at gmail.com
speeze.pearson at gmail.com
Sun Oct 11 18:35:45 EDT 2015
On Saturday, October 10, 2015 at 3:55:17 PM UTC-7, Steven D'Aprano wrote:
> # Solution 1: inject a new method into each and every instance in the tree.
> <snip>
> node.foo = MethodType(foo, node)
Ooh, interesting. I'll meditate on that for a while.
> # Solution 2: hack the node type of each instance.
> <snip>
> node.__class__ = MyNode
That is undoubtedly the coolest feature that I will absolutely never ever use.
> While both of the above have their uses, really the *right* way to do this
> is to stop being such an OOP purist. This isn't Java, we have functions for
> a reason.
> <snip>
> Do you find len(alist) to be confusing and schizophrenic?
Um-- no, because I'm used to it. ;)
I'll definitely give the functional approach another think-over.
If I do go down the functional road, and I decide that I need to associate my
own data with each node (e.g. for callback functions), would there be a better
way to do that than just adding my own attribute onto each node?
> class MyNode(Node):
> @property
> def parent(self):
> parent = super(MyNode, self).parent
> if parent is not None:
> parent = MyNode(parent)
> return parent
> # etc.
>
> Still a lot of work, and you really need to understand the original Node
> class very well. This is the problem with subclassing: it requires you to
> be intimately familiar with the *implementation details* of the class you
> subclass.
Hrm. Relying on implementation details of somebody else's library seems
dangerous... I think I'll shy away.
Thanks a lot!
-Spencer
More information about the Python-list
mailing list