2

我尝试在 python 中创建一个类(使用 XSI / Softimage)来覆盖默认方法。

class transform(object):
    def __init__ (self) :
        self.object = self._build()
        self.type = ''
    def _build (self):
        object = None
        return object
    @property
    def name(self):
        name = xsi.getValue(str(self.object) + '.Name')
        return str(name)    
    @name.setter
    def name(self, value):
        name = xsi.setValue(str(self.object) + '.Name', value)
        self.object = str(name)
    ################## TRANSLATE ######################
    @property
    def tx(self):
        tx = xsi.getValue(str(self.object) + '.kine.local.posx')
        return tx
    @tx.setter
    def tx(self, value):
        tx = xsi.setValue(str(self.object) + '.kine.local.posx', value)
    @property
    def ty(self):
        ty = xsi.getValue(str(self.object) + '.kine.local.posy')
        return ty
    @ty.setter
    def ty(self, value):
        ty = xsi.setValue(str(self.object) + '.kine.local.posy', value)
    @property
    def tz(self):
        tz = xsi.getValue(str(self.object) + '.kine.local.posz')
        return tz
    @tz.setter
    def tz(self, value):
        tz = xsi.setValue(str(self.object) + '.kine.local.posz', value) 

但正如你所看到的,我重复了很多。我怎样才能简化这个?也许与元类?

4

2 回答 2

4

您在这里不需要元类。你可以这样做:

def make_xsi_property(name):
    def get_prop(self):
        return xsi.getValue('{}.{}'.format(self.object, name))
    def set_prop(self, value):
        tx = xsi.setValue('{}.{}'.format(self.object, name), value)
    return property(get_prop, set_prop)

class MyClass(object):
    tx = make_xsi_property('kine.local.posx')
    ty = make_xsi_property('kine.local.posy')
    #...
于 2012-07-07T14:32:03.127 回答
3

property类型只是描述符的一个(方便的)快捷方式。对于您的情况,最简单的解决方案是自定义描述符,即:

class XsiDescriptor(object):
    def __init__(self, xsi):
        self.xsi = xsi

    def __get__(self, instance, cls=None):
        if instance is None:
            return self
        key = "%s.%s" % (instance.object, self.xsi)
        return xsi.getValue(key)

    def __set__(self, instance, value):
        key = "%s.%s" % (instance.object, self.xsi)
        xsi.setValue(key, value)


  class Transform(object):
      # your init etc here

      tx = XsiDescriptor("kine.local.posx")
      ty = XsiDescriptor("kine.local.posy")

      # etc
于 2012-07-07T14:38:06.637 回答