Jeroen Ruigrok van der Werven wrote: > Hi Bob, > > On 7/13/06, Bob Ippolito <[EMAIL PROTECTED]> wrote: >> Adding open classes would make it easier to develop DSLs, but you'd >> only be able to reasonably do one per interpreter (unless you mangled >> the class in a "with" block or something). > > The person whose 'complaints' I was stating says that DSLs (Domain > Specific Languages for those who, like me, were confused about the > acronym) are a big part of what he is after and one per interpreter is > fine by him. He also realises that the application(s) he needs them > for might be unusual. He doesn't specifically need the builtin types > to be extendable. It's just nice to be able to define a single class > in multiple modules. Even C++ allows this to some extent (but not as > much as he'd like).
I'm somewhat confused as to how Python's classes aren't open. Sure, types like the builtin types that don't have a __dict__ aren't open because there isn't anywhere to put the extensions, but metaclassing lets you do whatever you want to any other class: def extends(orig_cls): if not hasattr(orig_cls, "__dict__"): raise TypeError("Cannot extend %r" % cls) class ExtendMeta(type): def __new__(mcl, name, bases, ns): if len(bases) != 1: raise TypeError("Can only extend single class") if bases[0] is object: return type.__new__(mcl, name, bases, ns) for key, value in ns.iteritems(): if key not in ("__metaclass__", "__dict__"): setattr(orig_cls, key, value) return orig_cls class ExtendCls(object): __metaclass__ = ExtendMeta return ExtendCls >>> class A1(object): ... def method1(self): ... print "Hi, I'm method 1!" ... >>> class A2(extends(A1)): ... def method2(self): ... print "Hi, I'm method 2!" ... >>> x = A1() >>> x.method1() Hi, I'm method 1! >>> x.method2() Hi, I'm method 2! >>> y = A2() >>> y.method1() Hi, I'm method 1! >>> y.method2() Hi, I'm method 2! >>> A1 is A2 True Cheers, Nick. -- Nick Coghlan | [EMAIL PROTECTED] | Brisbane, Australia --------------------------------------------------------------- http://www.boredomandlaziness.org _______________________________________________ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com