python - 关于 Python 中的元类

标签 python class metaclass xsi

我尝试在 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) 

但如您所见,我重复了很多。我怎样才能简化这个?也许用元类?

最佳答案

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

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')
    #...

关于python - 关于 Python 中的元类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11375702/

相关文章:

c++ - 隐式调用构造函数

c++ - 循环依赖与可以相互初始化的类

python - 在 django 的元类中排除是什么意思?

unit-testing - 通过metaClass覆盖grails Controller 链方法无效

python - 如何验证 python 中的类属性?

python - 如何在递归函数中存储值?

python - Eclipse-pydev,在尝试导入 sqlite3 时出现 "Undefined variable from import: connect"

css - 是否可以在 css 伪类中执行第 n 个子级的第 n 个子级?

python - 使用 Django Migrations 删除表

python - 清除/覆盖 Python 中的标准输出