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

查看:29
本文介绍了__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()

推荐答案

您收到此错误是因为您没有将 data 变量传递给 DHT 构造函数.

You're receiving this error because you did not pass a data variable to the DHT constructor.

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天全站免登陆