Deciding inheritance at instantiation?

Nobody nobody at nowhere.com
Fri Aug 3 19:52:53 EDT 2012


On 2012年8月03日 13:48:08 -0700, Tobiah wrote:
> I have a bunch of classes from another library (the html helpers
> from web2py). There are certain methods that I'd like to add to
> every one of them. So I'd like to put those methods in a class,
> and pass the parent at the time of instantiation. Web2py has
> a FORM class for instance. I'd like to go:
>> 	my_element = html_factory(FORM)
>> Then my_element would be an instance of my class, and also
> a child of FORM.

You can use type() to create classes dynamically. E.g.:
	class my_base_class(object):
	 # extra methods
	subclasses = {}
	def html_factory(cls, *args, **kwargs):
	 name = "my_" + cls.__name__
	 if name not in subclasses:
	 subclasses[name] = type(name, (cls, my_base_class), {})
	 return subclasses[name](*args, **kwargs)


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /