为什么会出现AttributeError:“学生”对象没有属性“ displayStudent”

请让我知道为什么会出现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()

评论
ret
ret

When I ran your code I got an error in the class definition because def displayStudent was at a different indentation level from the def __init__. Fixed it up and it works fine:

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
点赞
评论
York
York

也许有一些缩进错误。这是正确的代码。

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()
点赞
评论