views:

203

answers:

1

I want to have compact class based python DSLs in the following form:

class MyClass(Static):
    z = 3
    def _init_(cls, x=0):
        cls._x = x

    def set_x(cls, x):
        cls._x = x

    def print_x_plus_z(cls):
        print cls._x + cls.z

    @property
    def x(cls):
        return cls._x

class MyOtherClass(MyClass):
    z = 6
    def _init_(cls):
        MyClass._init_(cls, x=3)

I don't want to write MyClass() and MyOtherClass() afterwards. Just want to get this working with only class definitions.

MyClass.print_x_plus_z()
c = MyOtherClass
c.z = 5
c.print_x_plus_z()
assert MyOtherClass.z == 5, "instances don't share the same values!"

I used metaclasses and managed to get _init_, print_x and subclassing working properly, but properties don't work. Could anyone suggest better alternative? I'm using Python 2.4+

A: 

To give a class (as opposed to its instances) a property, you need to have that property object as an attribute of the class's metaclass (so you'll probably need to make a custom metaclass to avoid inflicting that property upon other classes with the same metaclass). Similarly for special methods such as __init__ -- if they're on the class they'd affect the instances (which you don't want to make) -- to have them affect the class, you need to have them on the (custom) metaclass. What are you trying to accomplish by programming everything "one metalevel up", i.e., never-instantiated class with custom metaclass rather than normal instances of a normal class? It just seems a slight amount of extra work for no returns;-).

Alex Martelli