为什么会出现AttributeError:'Students'对象没有属性'displayStudent'

问题描述 投票:0回答:2

请让我知道为什么得到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()

python
2个回答
0
投票

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

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()

0
投票

[运行代码时,我在类定义中遇到了错误,因为def displayStudentdef __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
© www.soinside.com 2019 - 2024. All rights reserved.