【问题标题】:Why we get error like 'method takes 1 arguments 2 is given ' after removing self keyword?为什么我们在删除 self 关键字后得到类似“方法接受 1 个参数 2 给出”的错误?
【发布时间】:2020-03-14 12:35:57
【问题描述】:

为什么它显示 xyz 方法接受 1 个参数 2 在我将单个参数传递给该方法时给出,并且该方法也具有单个参数。当我将 self 关键字设置为方法的参数然后代码运行时没有错误时,我感到很困惑。请说明原因。

这里有两个代码sn-ps

  1. self:
class Demo:
    def show(self,x):
        print("hello {0}".format(x))
o2 = Demo()
o2.show("world")

# Output:
# hello world
  1. 没有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 的约定。

标签: python class object self


【解决方案1】:

在类函数方面,Python 与其他语言略有不同。

如果你在一个类里面定义了一个变量,它就是一个属于这个类的静态变量,就好像这个类是一个对象一样。因为类一个对象。这是一个 python 字典。

当您创建类的实例时,python 会复制 Dict 并为其命名。

为了创建实例变量,您需要将它们附加到实例 Dict 而不是类 Dict。

为了避免这两个字典之间的混淆,python 引入了“self”关键字。当 python 调用实例 Dict 上的函数时,它会将实例 Dict 的副本作为第一个参数传递给函数。

因此,要更改函数内的变量,您需要这样做:

class bicycle:
    numwheels = 2
    def __init__(self):
        # This is what python uses as the constructor
        self.numwheels = 3

    def changeInstanceWheels(self, wheelnum):
        self.numwheels = wheelnum
bike = bicycle()
print(bicycle.numwheels) # prints 2
print(bike.numwheels) # prints 3

bike.changeInstanceWheels(5)

print(bicycle.numwheels) # still prints 2 because this is the static variable
print(bike.numwheels) # prints 5

【讨论】:

    【解决方案2】:

    您调用该方法的实例隐含地是第一个参数(即self)。所以在这里,该方法有两个参数 - 调用它的 o2 和传递给它的 "ksr" ,并且因为它只需要一个参数而出错。

    【讨论】:

      【解决方案3】:

      当你在一个类中定义方法时,你必须包含一个强制性的第一个参数,例如selfx 参数之前,就像这样

      class Demo:
          def show(self, x):
              print("hello {0}".format(x))
      

      self 是一个保存 Demo 类实例的变量。

      您的方法当前只打印出x,并且它不使用任何类变量。你可以通过让你的方法像这样静态来避免使用self

      class Demo:
          @staticmethod
          def show(x):
              print("hello {0}".format(x))
      

      或者稍后在方法调用之前使用staticmethod 关键字将其转换为静态

      Demo.show = staticmethod(Demo.show)
      o2 = Demo()
      o2.show("world")
      

      通常首选第一个选项。

      【讨论】:

        猜你喜欢
        • 2018-03-24
        • 1970-01-01
        • 2016-02-28
        • 1970-01-01
        • 2020-03-08
        • 1970-01-01
        • 2020-12-29
        • 1970-01-01
        • 2017-12-29
        相关资源
        最近更新 更多