鱼C论坛

 找回密码
 立即注册
查看: 2608|回复: 3

[已解决]python3.6 函数中self参数出错问题

[复制链接]
发表于 2017-8-13 09:57:20 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
我用的是python3.6
在定义函数之后的参数self 之后调用会出错

代码如下:

>>> class Parent:
        def hello(self):
                print("lklll")

               
>>> t=Parent
>>> t.hello()
Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    t.hello()
TypeError: hello() missing 1 required positional argument: 'self'


什么情况?
最佳答案
2017-8-13 10:08:43
本帖最后由 shinemic 于 2017-8-13 10:13 编辑

在尝试中摸索:
  1. >>> class Parent:
  2. ...     def hello(self):
  3. ...         print('hello !')
  4. ...
  5. >>> t = Parent
  6. >>> t.hello()
  7. Traceback (most recent call last):
  8.   File "<stdin>", line 1, in <module>
  9. TypeError: hello() missing 1 required positional argument: 'self'
  10. >>> t.hello(t)
  11. hello !
  12. >>> t = Parent()
  13. >>> t.hello()
  14. hello !
复制代码

上面的代码中,首先和你一样:定义 Parent 类,并有方法 hello 进行输出;现在用代码 t = Parent  把 t 这个标签贴在 Parent 类上,也就是说,t成为了一个类对象,而不是实例化的对象,不是实例化的对象是没有 self 传进去的。self 是实例化之后,Python要知道他到底是哪个实例,比如说一个妈妈生了双胞胎,这双胞胎总要给他标记一下,比如这孩子脸上点个点。那么在程序里面定义函数时传入 self 参数,就能个性化了,不然只能共享父类的属性,一改全改。
但是你这里的 t.hello 没有实例化,所以 hello(self) 本来有个参数 self 指代实例本身,那当然「不存在」
所以需要实例化「t = Parent()」以后,带 self 参数的 t.hello() 才能正常运作(相当于t.hello(t)).
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2017-8-13 10:04:38 | 显示全部楼层
解决方法:t.hello(t)
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2017-8-13 10:08:43 | 显示全部楼层    本楼为最佳答案   
本帖最后由 shinemic 于 2017-8-13 10:13 编辑

在尝试中摸索:
  1. >>> class Parent:
  2. ...     def hello(self):
  3. ...         print('hello !')
  4. ...
  5. >>> t = Parent
  6. >>> t.hello()
  7. Traceback (most recent call last):
  8.   File "<stdin>", line 1, in <module>
  9. TypeError: hello() missing 1 required positional argument: 'self'
  10. >>> t.hello(t)
  11. hello !
  12. >>> t = Parent()
  13. >>> t.hello()
  14. hello !
复制代码

上面的代码中,首先和你一样:定义 Parent 类,并有方法 hello 进行输出;现在用代码 t = Parent  把 t 这个标签贴在 Parent 类上,也就是说,t成为了一个类对象,而不是实例化的对象,不是实例化的对象是没有 self 传进去的。self 是实例化之后,Python要知道他到底是哪个实例,比如说一个妈妈生了双胞胎,这双胞胎总要给他标记一下,比如这孩子脸上点个点。那么在程序里面定义函数时传入 self 参数,就能个性化了,不然只能共享父类的属性,一改全改。
但是你这里的 t.hello 没有实例化,所以 hello(self) 本来有个参数 self 指代实例本身,那当然「不存在」
所以需要实例化「t = Parent()」以后,带 self 参数的 t.hello() 才能正常运作(相当于t.hello(t)).
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 1 反对 0

使用道具 举报

发表于 2017-8-13 12:55:49 | 显示全部楼层
把t=Parent改为t=Parent()
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-5-10 14:51

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表