【问题标题】:Typerror using class in Python [duplicate]在Python中使用类的类型错误[重复]
【发布时间】:2021-02-22 22:01:11
【问题描述】:

我正在学习 Python 中的类和对象,但是当我运行此代码时,输​​出是一个错误。谁能告诉我如何解决它?

class Person :
def _init_ (self,name,age) :
    self.name = name
    self.age = age


def myfunction(self) :
        print("Hello My Name Is" + self.name)

 p1 = Person("John",36)
 p1.myfunction()

这是错误输出:

回溯(最近一次通话最后一次):文件“F:\IPB\PENUGASAN\SEMESTER 2\STRAKDAT\Penugasan\Pertemuan 3\Materi 3.py",第 16 行,在 p1 = Person("John",36) TypeError: Person() 没有参数

------------------(程序退出代码:1)

按任意键继续。 . .终止批处理作业 (Y/N)?

【问题讨论】:

  • __init__ 不是_init_(你需要双下划线)

标签: python class object


【解决方案1】:

两件事:
您的缩进设置不正确。
__init__ 应该带有双下划线。

试试这个:

class Person:
    def __init__(self,name,age) :
        self.name = name
        self.age = age


    def myfunction(self) :
        print("Hello My Name Is " + self.name)


p1 = Person("John",36)
p1.myfunction()

【讨论】:

    【解决方案2】:

    您的类中的_init_ 函数不是主要的初始化程序。为此,请将其重命名为 __init__

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-16
      • 2017-08-08
      • 1970-01-01
      • 1970-01-01
      • 2016-07-02
      • 1970-01-01
      • 2017-08-07
      • 2017-11-10
      相关资源
      最近更新 更多