How can I do with this method to get the result?

Viewed 58

I am new to Python. In this question I am trying to create a method in python so I can print out the student's information from my input:

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)

The input is:

t = student()
t.add_name('Sam')
t.add_age(21)
print(t)

I expect to get:

Name: Sam Age: 21

I tried many times in this code that gives the error message that "str is not callable" Thanks!

2 Answers

OK I see multiple problems

1- There is no add_name or add_age in the class to call.
2- To print the object of the created class as string, you need a string representation of that class or object. This representation done via __str__ method which returns the string representation.

The edited code would be

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

The input would be as is (with change of class name to Camel case (first letter is capital)

#only class name changed to be first letter is capital letter
t = Student()
t.add_name('Sam')
t.add_age(21)
print(t)

Output is

Name: Sam
Age: 21

I hope that answers the question

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
Related