如何向类中添加方法以及在python中在何处使用“self”

2024-10-01 17:39:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python语言的新手,我正在尝试理解self的概念。你知道吗

我已经定义了以下两个方法,我想知道需要在代码中做什么更改才能将它们包含在类中,以及在哪里使用self。你知道吗

import maya.cmds as cmds
# This function returns the animCurves connected to particular node 

def animCurveNode():

    animCurveName = []
    mySel = cmds.ls(sl = True)
    filePath = "D:\sdk.txt"
    attrName = "l_eyeBrow_Sliders.eyeBrow_start_updn"
    for each in mySel:
        list = cmds.listConnections(each, d = False,s = True)
        animCurveName.extend(list)

    return animCurveName

# This function return the animCurves and the name of the atribute to connect as the first memebr in the list

def attrAnimCurve():
    attrName = "l_eyeBrow_Sliders.eyeBrow_start_updn"
    animCurveNames = animCurveNode()
    animCurveNames.insert(0,attrName)
    return animCurveNames

Tags: thetoselfreturndefasfunctionthis
3条回答

self通常是类方法(绑定到类实例的函数)的第一个参数。self用作所讨论的reference to the object instance,因此用于读写该实例的属性。你知道吗

对象引用的显式传递还允许在类定义之外设置方法:

class Foo:
  def __init__(self, data):
    self.data = data
  def get(self): return self.data

foo = Foo([1,2,3])
Foo.get_data_as_set = lambda self: set(self.data)
print foo.get()
print Foo.get_data_as_set(foo)

上面的指纹

[1, 2, 3]
set([1, 2, 3])

谢谢你的回复。。。 我不明白什么变量应该是对象的一部分。 例如在我的代码中

class MyClass:

    # This method returns the animCurves connected to particular node
    def animCurveNode(self):

        animCurveName = []
        mySel = cmds.ls(sl = True)

还是应该

class MyClass:

    # This method returns the animCurves connected to particular node
    def animCurveNode(self):

        self.animCurveName = []
        self.mySel = cmds.ls(sl = True)  

你所拥有的不是方法。他们不在任何班级。请参见下面最简单的示例:

import maya.cmds as cmds


class MyClass:

    # This method returns the animCurves connected to particular node
    def animCurveNode(self):

        animCurveName = []
        mySel = cmds.ls(sl = True)
        filePath = "D:\sdk.txt"
        attrName = "l_eyeBrow_Sliders.eyeBrow_start_updn"
        for each in mySel:
            list = cmds.listConnections(each, d = False,s = True)
            animCurveName.extend(list)

        return animCurveName

    # This method return the animCurves and the name of the atribute to connect as the first memebr in the list
    def attrAnimCurve(self):
        attrName = "l_eyeBrow_Sliders.eyeBrow_start_updn"
        animCurveNames = animCurveNode()
        animCurveNames.insert(0,attrName)
        return animCurveNames

但是,您并没有真正指定要使用self的内容。例如,哪些变量应该是对象的一部分。你知道吗

有关self的更多信息,请看以下内容:

What is the purpose of self?

相关问题 更多 >

    热门问题