在python对象中使用self-parameter

wew*_*ewa 1 python class

我有一个关于在python中定义函数和自我参数的问题.

有以下代码.

class Dictionaries(object):
    __CSVDescription = ["ID", "States", "FilterTime", "Reaction", "DTC", "ActiveDischarge"]

    def __makeDict(Lst):
        return dict(zip(Lst, range(len(Lst))))

    def getDict(self):
        return self.__makeDict(self.__CSVDescription)

    CSVDescription = __makeDict(__CSVDescription)

x = Dictionaries()
print x.CSVDescription
print x.getDict()
Run Code Online (Sandbox Code Playgroud)

x.CSVDescription工作良好.但是print x.getDict()返回错误.

TypeError: __makeDict() takes exactly 1 argument (2 given)
Run Code Online (Sandbox Code Playgroud)

我可以self__makeDict()方法中添加-parameter ,但之后print x.CSVDescription就行不通了.

如何self正确使用-parameter?

Ilm*_*uro 6

在python中,该self参数被隐式传递给实例方法,除非该方法被装饰@staticmethod.

在这种情况下,__makeDict不需要引用对象本身,因此可以将其设置为静态方法,因此可以省略self:

@staticmethod
def __makeDict(Lst): # ...

def getDict(self):
    return self.__makeDict(self.__CSVDescription)
Run Code Online (Sandbox Code Playgroud)