我正在使用PyMel为Maya编写代码,我试图在我的装备类中创建一些属性来包装一些PyMel代码。所有属性的代码非常相似,所以我认为这是一个使用闭包的好地方。
import pymel.core as pm
import riggermortis.utils as utils
class RigModule(object):
def __init__:
# blah blah irrelevant code here
pass
def createRootProperty(attrName):
def getter(self):
return pm.getAttr(self.root+'.'+attrName)
def setter(self, nodeToLink):
if self.root.hasAttr(attrName):
pm.setAttr(self.root+'.'+attrName, nodeToLink)
else:
utils.linkNodes(self.root, nodeToLink, attrName)
return property(fget=getter,fset=setter)
hookConstraint = createRootProperty('hookConstraint')
unhookTarget = createRootProperty('unhookTarget')
moduleGrp = createRootProperty('moduleGrp')
hookGrp = createRootProperty('hookGrp')
功能上它可以工作,但Eclipse / PyDev告诉我我的' createRootProperty'功能需求'自我'作为它的第一个论点,所以我想知道我所做的是不正确的。
答案 0 :(得分:1)
对于你正在做的事情,除了清洁之外,真的不需要关闭。 linter认为它是一个格式不正确的成员函数,即使它正在做你想要的。
你可以移动类范围的功能,而linter将停止抱怨 - 你可以用下划线重命名这个函数,这样就没有人不小心认为它是一个工具而不是一个基础设施。
如果您希望这么做,您可以将其自动化为一个元类,该类从类字段中读取名称列表并根据需要创建特性。有一个更详细的策略示例here,但实质上,当定义类时,元类将获得类字典的副本,并且它有机会在编译之前弄乱定义。您可以在该步骤轻松创建属性:
def createRootProperty(name):
# this is a dummy, but as long as
# the return from this function
# is a property descriptor you're good
@property
def me(self):
return name, self.__class__
return me
class PropertyMeta(type):
# this gets called when a class using this meta is
# first compiled. It gives you a chance to intervene
# in the class creation project
def __new__(cls, name, bases, properties):
# if the class has a 'PROPS' member, it's a list
# of properties to add
roots = properties.get('PROPS', [])
for r in roots:
properties[r] = createRootProperty(r)
print ("# added property '{}' to {}".format(r, name))
return type.__new__( cls, name, bases, properties)
class RigModule(object):
__metaclass__ = PropertyMeta
PROPS = ['arm', 'head', 'leg']
def __init__(self):
pass
test = RigModule()
print test.arm
class Submodule(RigModule):
# metaclass added properties are inheritable
pass
test2 = Submodule()
print test2.leg
class NewProperties(RigModule):
# they can also be augmented in derived classes
PROPS = ['nose', 'mouth']
print NewProperties().nose
print NewProperties().arm
# added property 'arm' to RigModule
# added property 'head' to RigModule
# added property 'leg' to RigModule
# ('arm', <class '__main__.RigModule'>)
# ('leg', <class '__main__.Submodule'>)
# added property 'nose' to NewProperties
# added property 'mouth' to NewProperties
# ('nose', <class '__main__.NewProperties'>)
# ('arm', <class '__main__.NewProperties'>)
由于增加了复杂性,元类会得到一个糟糕的代表 - 有时是理所当然的。如果采用更简单的方法,请不要使用它们。但是对于像这样的情况下的样板减少,它们是一个很好的工具。