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"