【问题标题】:Python Class gives "None in the ouptut"Python 类给出“输出中没有”
【发布时间】:2013-05-18 07:07:15
【问题描述】:

我有以下代码:

class StudentData:
    "Contains information of all students"
    studentNumber = 0;
    def __init__(self,name,age,marks):
        self.name = name;
        self.age = age;
        self.marks = marks;
        StudentData.studentNumber += 1;
    def displayStudentNumber(self):
        print 'Total Number of students = ',StudentData.studentNumber;
    def displayinfo(self):
        print 'Name of the Student: ',self.name;
        print 'Age of the Student: ', self.age;
        print 'Marks of the Student: ', self.marks;

student1 = StudentData('Ayesha',12,90)
student2 = StudentData('Sarah',13,89)
print "*Student number in case of student 1*\n",student1.displayStudentNumber();
print "Information of the Student",student1.displayinfo();
print "*Student number in case of student 2*\n",student2.displayStudentNumber();
print "Information of the Student",student2.displayinfo();

输出是:

*学生1的学生编号* 学生总数 = 2 没有任何 学生姓名:Ayesha 学生年龄:12 学生成绩:90 没有任何 *学生2的学生人数* 学生总数 = 2 没有任何 学生信息学生姓名:Sarah 学生年龄:13 学生成绩:89 没有任何

我不明白为什么我的输出中会出现这些“无”。谁能解释一下?

【问题讨论】:

    标签: python linux class constructor


    【解决方案1】:

    您应该返回这些字符串,而不是打印它们。一个没有返回值的函数,返回None。另外不要在 Python 中使用分号。

    def displayStudentNumber(self):
          return 'Total Number of students = {0}'.format(StudentData.studentNumber)
    def displayinfo(self):
          return '''\
    Name of the Student: {0}
    Age of the Student: {1}
    Marks of the Student {2}'''.format(self.name, self.age, self.marks)
    

    【讨论】:

    • 我也为此 +1 了。 format() 是一个非常好的方法。
    • 但这对我来说有点复杂。我现在知道我在 Python 中很笨 :)
    • @AyeshaHassan 别担心,我们曾经都是 python 的初学者 :)
    【解决方案2】:

    因为您的函数 displayStudentNumber()displayinfo() 不返回任何内容。

    尝试将它们更改为:

    def displayStudentNumber(self):
        return 'Total Number of students = ' + str(StudentData.studentNumber)
    
    def displayinfo(self):
        print 'Name of the Student: ',self.name;
        print 'Age of the Student: ', self.age;
        print 'Marks of the Student: ', self.marks;
        return ''
    

    由于该函数不返回任何内容,因此默认为None。这就是它被退回的原因。

    顺便说一句,python中不需要分号。

    【讨论】:

    • @AyeshaHassan Lol,没问题。 :)
    【解决方案3】:

    您在输出中得到None,因为您正在打印调用方法displayStudentNumber 的返回值。默认情况下返回None

    您要么想要打印方法的返回值,要么只想打印。试试这样的,

    print "Student number in case of student 1"
    student1.displayStudentNumber()
    

    def displayStudentNumber(self):
        return 'Total Number of students = %d' % StudentData.studentNumber
    

    print "Student number in case of student 1", student1.displayStudentNumber()
    

    【讨论】:

      猜你喜欢
      • 2022-01-03
      • 2019-05-15
      • 1970-01-01
      • 2019-03-26
      • 1970-01-01
      • 1970-01-01
      • 2019-07-30
      • 2013-02-21
      • 2011-05-19
      相关资源
      最近更新 更多