【问题标题】:__init__() takes exactly 2 arguments (1 given)?__init__() 正好需要 2 个参数(给定 1 个)?
【发布时间】:2017-01-25 00:06:59
【问题描述】:

我想知道我落后的地方,寻求您的建议..

class Student_Record(object):

    def __init__(self,s):
        self.s="class_Library"
        print"Welcome!! take the benifit of the library"

    def Student_details(self):
        print " Please enter your details below"

a=raw_input("Enter your name :\n")
print ("your name is :" +a)
b=raw_input("Enter your USN :\n")
print ("Your USN is:" ,int(b))
c=raw_input("Enter your branch :\n")
print ("your entered baranch is" +c)
d=raw_input("Enter your current semester :\n")
print ("your in the semester",int(d))
rec=Student_Record()
rec.Student_details(self)

我收到这个错误..

TypeError: init() 只需要 2 个参数(给定 1 个)

【问题讨论】:

  • Student_Record() .. 忘记传递参数(对于s)。或者可能有一个参数太多?此外,rec.Student_details(self) 是错误的,因为 Python 自动self 参数提供给方法。
  • 代码说明Python基础要强制执行:除了报错,程序本身的逻辑也要调整

标签: python


【解决方案1】:

您的 Student_Record.__init__() 方法接受两个参数,selfsself是Python提供给你的,但是你没有提供s

您完全忽略了s,将其从函数签名中删除:

class Student_Record(object):
    def __init__(self):
        self.s = "class_Library"
        print"Welcome!! take the benifit of the library"

接下来,您将调用rec.Student_details() 方法并传入一个参数,但那个 方法只采用Python 已经为您提供的self。您不需要手动传递它,在您的情况下,该名称甚至没有在该范围内定义。

【讨论】:

    【解决方案2】:

    如果你这样做了

    class Student_Record(object):
    
        def __init__(self, s):
            self.s = ""
    
        def Student_details(self):
            print " Please enter your details below"
    

    当您创建 Student_Record 类的对象时,它应该接受一个参数,尽管它本身 (self)。所以它看起来像:

    record = Student_Record("text")
    

    __init__ 中,您可以对传入的变量s 执行任何操作。例如,self.s = s,您可以在类中的任何位置使用self.s 调用它,因为它已被初始化。

    【讨论】:

      【解决方案3】:

      你的代码应该是这样的......(python缩进):

      class Student_Record(object):
      
          def __init__(self,s="class_Library"):
              self.s=s
              print"Welcome!! take the benifit of the library"
      
          def Student_details(self):
              print " Please enter your details below"
              a=raw_input("Enter your name :\n")
              print ("your name is :" +a)
              b=raw_input("Enter your USN :\n")
              print ("Your USN is:" ,int(b))
              c=raw_input("Enter your branch :\n")
              print ("your entered baranch is" +c)
              d=raw_input("Enter your current semester :\n")
              print ("your in the semester",int(d))
      
      rec=Student_Record()
      
      rec.Student_details()
      

      def __init__ 中的s 应该有一个默认值,或者您可以从rec=Student_Record() 传递一个值。

      【讨论】:

        猜你喜欢
        • 2015-07-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多