我正在为一个项目撰写Python脚本,但我对该语言很新。我感到困惑的是静态变量的用法。这是我目前正在处理的代码:

class panelToggle(bpy.types.Operator):
    active = False

    def invoke(self, context, event):
        self.active = not self.active
        return{'FINISHED'}

class OBJECT_OT_openConstraintPanel(panelToggle):
    bl_label = "openConstraintPanel"
    bl_idname = "openConstraintPanel"

想法是第二类应该继承 积极的 变量和 调用 第一个方法,因此调用object_ot_openconcontraintpanel.invoke()更改object_ot_openconconstraintpanel.active。使用 自己 但是,正如我上面所做的那样,但是也没有使用 planteToggle 反而。对我如何做的任何想法吗?

有帮助吗?

解决方案

采用 type(self) 用于访问类属性

>>> class A(object):
 var  = 2
 def write(self):
  print type(self).var
>>> class B(A):
 pass
>>> B().write()
2
>>> B.var = 3
>>> B().write()
3
>>> A().write()
2

其他提示

您可以访问 active 通过班级属于:

if panelToggle.active:
    # do something

如果您想访问 班级 从方法中的变量,您可以编写:

def am_i_active(self):
    """ This method will access the right *class* variable by
        looking at its own class type first.
    """
    if self.__class__.active:
        print 'Yes, sir!'
    else:
        print 'Nope.'

可以在这里找到一个工作示例: http://gist.github.com/522619


self 变量(命名 self 按照惯例)是该类的当前实例,隐含地通过但明确收到。

class A(object):

    answer = 42

    def add(self, a, b):
        """ ``self`` is received explicitely. """
        return A.answer + a + b

a = A()

print a.add(1, 2) # ``The instance -- ``a`` -- is passed implicitely.``
# => 45

print a.answer 
# => print 42
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top