我是Python新手。在这个问题中,我试图在python中创建一个方法,这样我就可以从输入中打印出学生的信息:
class student():
def __init__(self,s=None):
if (s != None):
self.name = s[0]
self.age = s[1]
else:
self.name = ''
self.age = -1
def print_info(self):
print('Name: ',self.name)
print('Age: ',self.age)
输入是:
t = student()
t.add_name('Sam')
t.add_age(21)
print(t)
我希望得到:
姓名:山姆 年龄:21
我在这段代码中多次尝试过,提供错误信息" str不可调用" 谢谢!
答案 0 :(得分:1)
好的,我看到了多个问题
1-班级中没有add_name
或add_age
可供使用
2-要将创建的类的对象作为字符串打印,需要该类或对象的字符串表示形式。此表示通过__str__
方法完成,该方法返回字符串表示形式。
编辑后的代码为
#Added inheritance of `object` as good practice
#and changed the name to make the first letter as capital
class Student(object):
def __init__(self, s=None):
if s is not None:
self.name = s[0]
self.age = s[1]
else:
self.name = ''
self.age = -1
#added two missing methods to set the name and the age
def add_name(self, name):
self.name = name
def add_age(self, age):
self.age = age
#added the method responsible for string representation
#of the object and the age converted to string using similar method
def __str__(self):
return 'Name: ' + self.name + '\n' + 'Age: ' + self.age.__str__()
def print_info(self):
print('Name: ', self.name)
print('Age: ', self.age)
输入将按原样输入(将类名更改为Camel案例(首字母为大写)
#only class name changed to be first letter is capital letter
t = Student()
t.add_name('Sam')
t.add_age(21)
print(t)
输出
姓名:Sam
年龄:21
我希望能回答这个问题
答案 1 :(得分:0)
class student():
def __init__(self,s=None):
if (s != None):
self.name = s[0]
self.age = s[1]
else:
self.name = ''
self.age = -1
def __repr__(self):
print('Name: ',self.name)
print('Age: ',self.age)
def __str__(self):
return 'Name: ' + self.name + '\n' + 'Age: ' + self.age.__str__()
def add_name(self,name):
self.name = name
def add_age(self,age):
self.age = age