Ruby Impressions
Alex Martelli
aleax at aleax.it
Sat Jan 12 09:11:04 EST 2002
Adam Spitz wrote:
...
> get a syntax more intuitive than this (with either version):
>
> class Person:
> def __extra_init__(self):
> self.doSomeStuff()
>
> init_attributes(Person, "name", "age", "gender")
>
> You see? We can create an init_attributes method that generates the
> __init__ method that we want, but we can't *call* the init_attributes
> method until after the class has already been defined, which means
> that we have to put it *underneath* the class definition, which is a
Or, you can choose to use a metaclass (e.g. in Python 2.2):
class Person:
__metaclass__ = AS
_init_attributes = "name age gender"
def _extra_init(self): self.doSomeStuff()
Would that meet your criteria? Instead of assigning the metaclass in the
class body, you could assign it as a module global variable, or inherit
Person from an ASmixin class that defines __metaclass__, etc.
As a first, rough approximation, you can think of a metaclass as a way to
perform something on a class-object *while* the class object is being
created. You should therefore think of metaclasses any time you feel
constrained, as you put it here, by needing to do things "after" the class
object is created. Python 2.2 makes it quite easy for you to develop your
own metaclasses, after all -- for metaclasses that imply modestly-different
handling from that of normal classes, you can inherit from builtin type
'type' and override things as you desire.
If you do have an existing function init_attributes that performs just what
you wish when called as above, for example:
class AS(type):
def __init__(self, name, bases, classdict):
type.__init__(self, name, bases, classdict)
init_attributes(self,
*classdict.get('_init_attributes','').split())
Not too bad, isn't it?
> By now, I'm sure most of you are thinking, "Who cares? Just write out
> the __init__ method the normal way. It's not so bad." And you're
> right. It's really not a big deal. In fact, forget that I said
> anything. Python is good enough. Really.
I agree. However, metaclasses do give you just that little tad of extra
flexibility that, some of the time, may let you improve your solutions from
"good enough" to "just to your tastes".
Alex
More information about the Python-list
mailing list