>>> class x(object):
... def __metaclass__(name, bases, dict):
... print "hello"
... return type(name, bases, dict)
...
hello
>>>
instead of defining a separate metaclass function/class, you can do
it inline. isn't that cool?
-tomer
But why use a metaclass? If the meta class is only applied to *one*
class, can't you do at class level whatever the metaclass is doing!?
Ciao,
Marc 'BlackJack' Rintsch
Most but not all of the "whatever". E.g.:
class X:
class __metaclass__(type):
def __str__(cls): return 'The great class X!'
print X
You can't make "print X" behave arbitrarily w/o a custom metaclass.
Alex
The very fact that you can put a loop inside __metaclass__ may be reason
enough for a one-off metaclass.
Here's a contrived example:
class X :
def __metaclass__( name, bases, dict ) :
for k,v in dict.items() :
if k.startswith('get_') :
dict[ k[4:].upper() ] = property( v )
return type( name, bases, dict )
def get_a( self ) :
...
def get_b( self ) :
...
o = X()
print o.A
print o.B
> Marc 'BlackJack' Rintsch wrote:
>> But why use a metaclass? If the meta class is only applied to *one*
>> class, can't you do at class level whatever the metaclass is doing!?
>
> The very fact that you can put a loop inside __metaclass__ may be reason
> enough for a one-off metaclass.
Ah, it's not the loop but the access to the `dict`! You can write loops
at class level too but I haven't found a way to access `X`s `__dict__`
because `X` does not exist at this point.
> Here's a contrived example:
>
> class X :
> def __metaclass__( name, bases, dict ) :
> for k,v in dict.items() :
> if k.startswith('get_') :
> dict[ k[4:].upper() ] = property( v )
> return type( name, bases, dict )
>
> def get_a( self ) :
> ...
>
> def get_b( self ) :
> ...
>
>
> o = X()
> print o.A
> print o.B
BTW, if that's what gangesmaster is after then it seem to work already.
Put ``(object)`` after ``X`` and return something, say 'a' and 'b', in the
getters and the example prints 'a' and 'b'.
Ciao,
Marc 'BlackJack' Rintsch
You're right. I guess i wasn't clear in my previous post, but I was
referring to 'the ability to process the dict (say, using loops)'
> BTW, if that's what gangesmaster is after then it seem to work already.
> Put ``(object)`` after ``X`` and return something, say 'a' and 'b', in the
> getters and the example prints 'a' and 'b'.
btw, the example seems to work even with old-style classes.
Regards
Sreeram
>> BTW, if that's what gangesmaster is after then it seem to work already.
>> Put ``(object)`` after ``X`` and return something, say 'a' and 'b', in the
>> getters and the example prints 'a' and 'b'.
>
> btw, the example seems to work even with old-style classes.
Yes, but setting properties works only with new-style classes. So I use
them whenever I use properties. In my mind properties and new-style
classes are linked together.
Ciao,
Marc 'BlackJack' Rintsch