请让我知道为什么得到AttributeError:'Students'对象没有属性'displayStudent'
全班学生:def init(自身,名称,年龄):self.name =名字self.age =年龄班级学生:def init(自身,名称,年龄):self.name =名字self.age =年龄
def displayStudent(self):
return("Student name is" + self.name + "and age is" + str(self.age))
stu =学生(“乍得”,15)stu.displayStudent()
也许存在一些缩进错误。这是正确的代码。
class Students:
def __init__(self, name, age):
self.name = name
self.age = age
def displayStudent(self):
return "Student name is " + self.name + " and age is " + str(self.age)
stu = Students("Chad", 15)
stu.displayStudent()
[运行代码时,我在类定义中遇到了错误,因为def displayStudent
与def __init__
处于不同的缩进级别。修复它,它可以正常工作:
class Students:
def __init__(self, name: str, age: int) -> None:
self.name = name
self.age = age
def displayStudent(self) -> None:
print(f"Student name is {self.name} and age is {self.age}")
stu = Students("Chad", 15)
stu.displayStudent()
Student name is Chad and age is 15