Skip to main content
 首页 » 编程设计

python之我该如何使用这种方法来获得结果

2025年02月15日9yxwkf

我是 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 is not callable”的错误消息 谢谢!

请您参考如下方法:

好的,我看到了多个问题

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) 

输出是

Name: Sam
Age: 21

我希望这能回答问题