__init __()缺少1个必需的位置参数 [英] __init__() missing 1 required positional argument

查看:219
本文介绍了__init __()缺少1个必需的位置参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习Python。这是一个非常简单的代码。我在这里要做的就是调用类的构造函数。在那里初始化一些变量并打印该变量。但这给了我一个错误。就是说:

I am trying to learn Python. This is a really simple code. All I am trying to do here is to call a class's constructor. Initialize some variables there and print that variable. But it is giving me an error. It is saying:


缺少1个必需的位置自变量

missing 1 required positional argument

这是我的代码:

class DHT:
    def __init__(self, data):
        self.data['one'] = '1'
        self.data['two'] = '2'
        self.data['three'] = '3'
    def showData(self):
        print(self.data)

if __name__ == '__main__': DHT().showData()


推荐答案

由于没有传递数据变量。

aIKid和Alexander的答案很不错,但是它行不通,因为您仍然必须初始化 self.data 在类构造函数中是这样的:

aIKid and Alexander's answers are nice but it wont work because you still have to initialize self.data in the class constructor like this:

class DHT:
   def __init__(self, data=None):
      if data is None:
         data = {}
      else:
         self.data = data
      self.data['one'] = '1'
      self.data['two'] = '2'
      self.data['three'] = '3'
   def showData(self):
      print(self.data)

然后调用如下所示的showData方法:

And then calling the method showData like this:

DHT().showData()

还是这样的:

DHT({'six':6,'seven':'7'}).showData()

或类似这样:

# Build the class first
dht = DHT({'six':6,'seven':'7'})
# The call whatever method you want (In our case only 1 method available)
dht.showData()

这篇关于__init __()缺少1个必需的位置参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆