小编Dav*_*vid的帖子

Pythonic方式动态添加属性和setter

我正在开发一个用于3D应用程序的库,它将应用程序的功能包装到一组Python类中,并添加应用程序没有的其他功能.

我的基类中有一组属性,用于使用现有API向节点添加属性,但我想要一种更优雅的方式来动态添加属性.我目前有这个代码(如果不熟悉3D应用程序可能没什么意义),但重要的是

# Add block properties
Run Code Online (Sandbox Code Playgroud)

# PROPERTIES
Run Code Online (Sandbox Code Playgroud)

码.

class Block(pyunify.Transform):
    def __init__(self, name = "Character"):
        pyunify.Transform.__init__(self, name)
        self.LockTransform()


class Spine(Block):
    def __init__(self, name = "Character", numberOfJoints=6):
        Block.__init__(self, name+"_spine")

        # Add block properties
        self.AddAttr("numberOfJoints", "long")
        self.SetAttr("numberOfJoints", numberOfJoints)

        # Create block template
        self.Template()

    # PROPERTIES
    @property
    def numberOfJoints(self):
        return self.GetAttr("numberOfJoints")

    @numberOfJoints.setter
    def numberOfJoints(self, num):
        self.SetAttr("numberOfJoints", num)
Run Code Online (Sandbox Code Playgroud)

因此,我可以预见其他类具有更多属性,以及我现在的方式,我必须在_init__中添加它的每个属性

self.AddAttr("numberOfJoints", "long")
self.SetAttr("numberOfJoints", numberOfJoints)
Run Code Online (Sandbox Code Playgroud)

然后我必须在我的类中添加另外两个函数,一个getter和setter,用于该属性,以便我可以在我的类中调用它作为self.numberOfJoints,它将与类本身交互以及设置正确的属性3D应用程序中的伴随节点.

    @property
    def numberOfJoints(self):
        return self.GetAttr("numberOfJoints")

    @numberOfJoints.setter
    def numberOfJoints(self, num):
        self.SetAttr("numberOfJoints", num)
Run Code Online (Sandbox Code Playgroud)

与附加属性函数的唯一区别是名称,所以我想知道是否有一种方法可以在我的基类Block类中创建一个AddProperty函数,这样我就可以在我的_init__函数中执行此操作:

self.AddProperty("numberOfJoints", "long")
self.numberOfJoints = 5
Run Code Online (Sandbox Code Playgroud)

除了运行当前_init__行之外,它还将动态创建getter和setter函数 …

python properties class maya

3
推荐指数
1
解决办法
8039
查看次数

如何让Linux脚本在受保护的目录中访问mkdir而无需在Linux中进行su访问?

我正在尝试创建一个python shell脚本来在Ubuntu Linux中创建许多目录.我正在尝试创建目录的主目录受到写访问保护.有没有办法允许Python脚本在那里创建目录,好像它是root用户,但不必通过su运行脚本,因为其他用户可能需要运行脚本但不应该有su访问权限?

python linux filesystems shell

1
推荐指数
1
解决办法
1668
查看次数

标签 统计

python ×2

class ×1

filesystems ×1

linux ×1

maya ×1

properties ×1

shell ×1