python TypeError: missing 1 required positional argument:'self'

简介: python TypeError: missing 1 required positional argument:'self'

python TypeError: missing 1 required positional argument:'self'


Python 调用类的函数时报错如下:

TypeError: seperate_data() missing 1 required positional argument:'self'

报错原因:

train_data, test_data =  DataCleaner.seperate_data()

DataCleaner 是个类,seperate_data() 是其中的方法,不能直接这样调用,需要先将类实例化。

代码改为:

train_data, test_data =  DataCleaner().seperate_data()

注意:DataCleaner 是类,DataCleaner() 是类的对象。

代码原理:

调用 object 的函数(如下边的  A().t() )的时候会自动把自己作为第一个参数传进去,就是 self,而直接通过 类(就是不加括号的方式)调用函数不会,所以会报错。见下图:

解释:

A是 class 也就是类

A() 是object 也就是对象

A.t() 就是调用类的方法

A().t()就是调用对象的方法

以上,问题解决~

相关文章
Python错误 TypeError: ‘NoneType‘ object is not subscriptable解决方案汇总
Python错误 TypeError: ‘NoneType‘ object is not subscriptable解决方案汇总
|
9天前
|
Python
|
11天前
|
Python
Python中参数解包(Argument Unpacking)
【6月更文挑战第10天】
10 3
|
11天前
|
Python
|
23天前
|
Python 索引 容器
Python中类型错误(TypeError)
【6月更文挑战第1天】
24 5
|
1月前
|
索引 Python
python类型错误(TypeError)
【5月更文挑战第1天】
134 2
|
1月前
|
Java 程序员 编译器
Python 为什么要保留显式的 self ?
Python 为什么要保留显式的 self ?
26 2
|
1月前
|
Python
Python类(class)中self的理解
Python类(class)中self的理解
24 0
|
1月前
|
算法 开发者 Python
【Python 基础扫盲 】self参数、__init__方法和.__str__方法的用处和区别?
【Python 基础扫盲 】self参数、__init__方法和.__str__方法的用处和区别?
35 0
|
7月前
|
C++ 开发者 Python
46 python - self
46 python - self
22 0