我正在做一些Python练习,似乎无法解决这个错误。

huangapple go评论59阅读模式
英文:

I'm doing some Python exercises and can't seem to get around this error

问题

class Student:

     def get_name(self):
            """返回当前学生对象的名字。"""
            return self.name
    
     def get_age(self):
            """返回当前学生对象的年龄。"""
            return self.age
    
     def say_hello(self, message=None) -> None:
            if message is not None:
                print(f"{self.name} 说: {message}")
            else:
                print(f"你好,我叫{self.name}。很高兴认识你!")

if __name__ == '__main__':

        student = Student(name='Wes', age=10)
        name = student.get_name()
        age = student.get_age()
    
        student.say_hello()
    
        message = f"学生的名字是{name}。他们的年龄是{age}。"
        student.say_hello(message)

我得到了这个错误:

File “student.py”, line 21, in <module> student = Student(name=‘Wes’, age=10) TypeError: Student()不接受参数

而这应该是期望的结果:

你好,我叫Wes。很高兴认识你!

Wes 说: 学生的名字是Wes。他们的年龄是10。
英文:
class Student:

     def get_name(self):
            """Return the name of current Student object."""
            return self.name
    
     def get_age(self):
            """Return the age of the current Student object."""
            return self.age
    
     def say_hello(self, message=None) -> None:
            if message is not None:
                print(f"{self.name} says: {message}")
            else:
                print(f"Hello, my name is {self.name}. Nice to meet you!")

if __name__ == '__main__':

        student = Student(name='Wes', age=10)
        name = student.get_name()
        age = student.get_age()
    
        student.say_hello()
    
        message = f"The student's name is {name}. Their age is {age}."
        student.say_hello(message)

I get this error:

File “student.py”, line 21, in <module> student = Student(name=‘Wes’, age=10) TypeError: Student() takes no arguments

when this is supposed to be the result:

Hello, my name is Wes. Nice to meet you!

Wes says: The student's name is Wes. Their age is 10.

答案1

得分: 1

你已经定义了Student类,但没有def __init__方法,如果你想在初始化新的类实例时传递参数,需要添加以下代码到你的类定义的顶部:

def __init__(self, name, age):
    self.name = name
    self.age = age
英文:

You have defined Student class without a def __init__ method required if you want to send arguments when initiating a new class instance. Add:

def __init__(self, name, age):
    self.name = name
    self.age = age

as a method at the top of your class definition.

huangapple
  • 本文由 发表于 2023年2月14日 06:32:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/75441814.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定