当定义在其上方时,“学生”未定义

时间:2019-09-28 14:29:51

标签: python class

class Student:
    def __init__(Sname,Stnumber,Cnumber,IDnumber):
        self.Sname=''
        self.Stnumber=0
        self.Cnumber=0
        self.IDnumber=0

    sn=input("Enter Studentname:")
    stn=input("Enter Student number:")
    cn=input("Enter Contact number:")
    ID=input("Enter ID number:")

    StudentObj= Student(sn,stn,cn,ID)

错误:

NameError                                 Traceback (most recent call last)
<ipython-input-1-f3e61d3c7d24> in <module>()
----> 1 class Student:
      2     def __init__(Sname,Stnumber,Cnumber,IDnumber):
      3         self.Sname=''
      4         self.Stnumber=0
      5         self.Cnumber=0

<ipython-input-1-f3e61d3c7d24> in Student()
     23     ID=input("Enter ID number:")
     24 
---> 25     StudentObj= Student(sn,stn,cn,ID)

NameError: name 'Student' is not defined

2 个答案:

答案 0 :(得分:1)

您有缩进问题,只需将输入和对象声明移到class定义之外:

class Student:
    def __init__: ...
    def populate: ...
    def display: ...

sn = input("Enter Student name:")
stn = input("Enter Student number:")
cn = input("Enter Contact number:")
ID = input("Enter ID number:")

StudentObj = Student(sn, stn, cn, ID)
StudentObj.display()

您还缺少self方法的声明中的参数__init__

答案 1 :(得分:1)

class Student:
    def __init__(self, Sname='', Stnumber=0, Cnumber=0, IDnumber=0):
        self.Sname=Sname
        self.Stnumber=Stnumber
        self.Cnumber=Cnumber
        self.IDnumber=IDnumber

    def populate(self,sn,stn,cn,ID):
        self.Sname=sn
        self.Stnumber=stn
        self.Cnumber=cn
        self.IDnumber=ID

    def display(self):
        print("Student name is:",self.Sname)
        print("Student number is:",self.Stnumber)
        print("Contact number is:",self.Cnumber)
        print("ID number is:",self.IDnumber)

sn=input("Enter Studentname:")
stn=input("Enter Student number:")
cn=input("Enter Contact number:")
ID=input("Enter ID number:")

StudentObj= Student(sn,stn,cn,ID)
StudentObj.display()

您犯了几个错误。

首先,启动sn的选项卡将使其生效,使其仍位于类内。在python中,您需要注意制表符。

此外,您还需要在__init__中添加self作为能够使用它的第一个参数。

即使在此之后的第三次,您的代码也将仅显示0,'','',``'',因为您没有在构造函数中分配变量,我已经这样做了