Python 如何在if语句中调用类的方法?

Python 如何在if语句中调用类的方法?,python,Python,您的代码有几个问题。要使代码运行,应至少修复以下问题: 将类Stud移到顶部-不应在方法定义之前调用该方法 通过stud对象调用方法stud-这意味着您应该首先创建stud类的对象 以下是代码的工作版本: choice= input("Enter your choice") if choice== 1: print("Add Student") student_id= int(input("Enter the students ID"))

您的代码有几个问题。要使代码运行,应至少修复以下问题:

  • 将类Stud移到顶部-不应在方法定义之前调用该方法
  • 通过stud对象调用方法stud-这意味着您应该首先创建stud类的对象
以下是代码的工作版本:

choice= input("Enter your choice")

if choice== 1:
        print("Add Student")

        student_id= int(input("Enter the students ID"))
        student_name= raw_input("Enter the students Name")
        student_standard= raw_input("Enter the students standard")
        Stud().stud(student_id,student_name,student_standard)

        print("Added Successfully")

else:
    print "Invalid Choice"


class Stud:

    def stud(self,student_id,student_name,student_standard):

        self.student_id=student_id
        self.student_name=student_name
        self.student_standard=student_standard

        return "Student's id=",self.student_id
        return "Student's name=",self.student_name
        return "student's standard=",self.student_standard

您当前的代码有什么问题?您正确地调用了该方法。类的问题在于:您应该将设置代码分为
\uuu init\uuu
,并且您只能
从给定的函数调用返回
一次。您的意思是
在函数中打印
而不是
返回
输入
返回字符串,因此
选择
永远不会是
1
,而是
“1”
choice= input("Enter your choice")
class Stud:

    def stud(self,student_id,student_name,student_standard):

        self.student_id=student_id
        self.student_name=student_name
        self.student_standard=student_standard

        return "Student's id=",self.student_id
        return "Student's name=",self.student_name
        return "student's standard=",self.student_standard

if choice== 1:
        print("Add Student")

        student_id= int(input("Enter the students ID"))
        student_name= raw_input("Enter the students Name")
        student_standard= raw_input("Enter the students standard")
        stud = Stud()
        stud.stud(student_id,student_name,student_standard)

        print("Added Successfully")

else:
    print "Invalid Choice"