调用一个使用 class 中另一个方法的变量的方法

Calling a method which uses variables from another method in a class

我正在 Maya 中编写脚本并尝试在另一个方法中分配变量,而不是像我们通常那样在 __init__ 中分配变量。我将我的 window 命令放在 __init__ 中,所以当一个新实例被初始化时,如果我们在 __init__ 中分配变量,它会一直 运行 而不分配变量我想要的价值。

例如:

    def __init__(self, windowID = 'selectsomething', title = 'select something'):
        self.windowID = windowID
        self.title = title

        if cmds.window(self.windowID, exists = True):
            cmds.deleteUI(self.windowID)
                    
        myWindow = cmds.window(self.windowID, title = self.title)
        cmds.rowColumnLayout(numberOfColumns = 2, columnWidth = [(1, 300), (2, 100)],
                             columnAttach = [1, 'left', 10], columnSpacing = [1, 10],
                             rowSpacing = [1, 5])
        cmds.button(label = "Apply", command = self.applyButton) #it should print out selected object
        cmds.button(label = "Cancel", command = self.cancelButton)
        cmds.showWindow(myWindow)

        #now for example if I have a sel variable to store selected objects, it would actually return nothing cuz the code ran all the way through and didnt wait for me to select what I needed
        sel = cmds.ls(selection = True) #this will return nothing

我的解决方案是在 applyButton 方法中分配变量,它将存储我选择的内容。我发现从该方法本身调用一个使用另一个方法的变量的方法有点奇怪。

例如:

class Abc:
    def func(*arg):
        print(self.var)
    
    def var(self):
        self.var = 1
        self.func()
        
abc = Abc()
abc.var()

现在的代码是 运行s,但是调用 func 方法听起来是不是有点奇怪,它使用 var 方法中的变量 var 方法本身?

我还没有看到有人这样做过。我的意思是没有 class,在函数内部分配的变量保留在该函数内部,我们只能将它与 return 一起使用。但是看起来在 class 中我们可以通过在它之前添加 self. 来使任何内部方法变量成为全局变量?

我的朋友也说我们可以在这种情况下使用 @property 但我想我还没有弄明白。

您需要注意 数据属性 是 class 的隐式成员,因此可以被同一 class 中的任何方法使用在他们被分配到某个地方之后。

来自Python documentation

Data attributes need not be declared; like local variables, they spring into existence when they are first assigned to.

虽然您的示例可以工作(如果您在 Abc.func() 之前调用 Abc.var()),恕我直言,像这样在 class 级别初始化变量会更好(请注意,我将其命名为 val 以避免与方法名称混淆):

class Abc:
    val = 0

    def func(self, *arg):
        print(self.val)

    def var(self):
        self.val = 1
        self.func()

self 关键字的用途得到了很好的解释 here and here

另请注意,在 __init__ 方法内初始化属性会将此属性绑定到 class 实例,而在 __init__ 方法外初始化会将其绑定到 class 本身,这是另一回事(参见 this discussion)。