【发布时间】:2020-03-14 12:35:57
【问题描述】:
为什么它显示 xyz 方法接受 1 个参数 2 在我将单个参数传递给该方法时给出,并且该方法也具有单个参数。当我将 self 关键字设置为方法的参数然后代码运行时没有错误时,我感到很困惑。请说明原因。
这里有两个代码sn-ps
- 与
self:
class Demo:
def show(self,x):
print("hello {0}".format(x))
o2 = Demo()
o2.show("world")
# Output:
# hello world
- 没有
self:
class Demo:
def show(x):
print("hello {0}".format(x))
o2 = Demo()
o2.show("world")
# Output:
# Traceback (most recent call last):
# File "main.py", line 7, in <module>
# o2.show("ksr")
# TypeError: show() takes exactly 1 argument (2 given)
【问题讨论】:
-
类方法隐式接收类实例作为
self参数。当您调用o2.show(...)时,o2会作为第一个参数隐式传递给函数,名称为self。基本上,o2.show("world")与Demo.show(o2, "world")相同。另外值得注意的是 - 您可以将单词self更改为您喜欢的任何单词,这只是使用self的约定。