Skip to main content
 首页 » 编程设计

python之在 python 对象中使用自参数

2025年05月04日10傻小

我有一个关于在 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() 

x.CSVDescription 工作正常。但是 print x.getDict() 返回错误。

TypeError: __makeDict() takes exactly 1 argument (2 given) 

我可以将 self 参数添加到 __makeDict() 方法,但是 print x.CSVDescription 将不起作用。

如何正确使用 self 参数?

请您参考如下方法:

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

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

@staticmethod 
def __makeDict(Lst): # ... 
 
def getDict(self): 
    return self.__makeDict(self.__CSVDescription)