Adding methods to a class

Let's add some methods to our Student class that would help retrieve a student's information:

class Student(object): 
"""A Python class to store student information"""

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

def return_name(self):
"""return student name"""
return self.name

def return_age(self):
"""return student age"""
return self.age

def return_address(self):
"""return student address"""
return self.address

In this example, we have added three methods namely return_name(), return_age() and return_address() that returns the attributes name, age and address respectively. These methods of a class are called callable attributes. Let's review a quick example where we make use of these callable attributes to print an object's information.

student1 = Student("John Doe", "29", "123 Main Street, Newark, CA") 
print(student1.return_name())
print(student1.return_age())
print(student1.return_address())

So far, we discussed methods that retrieves information about a student. Let's include a method in our class that enables updating information belonging to a student. Now, let's add another method to the class that enables updating address by a student:

def update_address(self, address): 
"""update student address"""
self.address = address
return self.address

Let's compare the student1 object's address before and after updating the address:

print(student1.address()) 
print(student1.update_address("234 Main Street, Newark, CA"))

This would print the following output to your screen:

    123 Main Street, Newark, CA
234 Main Street, Newark, CA

Thus, we have written our first object-oriented code that demonstrates the ability to modularize the code. The preceding code sample is available for download along with this chapter as student_info.py.