英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论