CP164 Study Guide - Final Guide: Init, Docstring

18 views2 pages
13 Jun 2018
School
Course
Professor
Notes - Class Methods
Special Python Methods
The Student class contains a number of other methods, some of which have special
meanings in Python. Python identifies special methods by surrounding their names with
double underscores, as we have already seen with the __init__ constructor method. These
special methods are not called by their names, but instead are called using familiar Python
functions or operators. The __init__ constructor, for example, is never called by the
name __init__, but rather by simply using the name of the class as the constructor call.
The __str__ Method
When defined in a class, the __str__ method returns a string version of the attributes of an
object. This string can be used anywhere that a Python string can be used - in printing,
concatenation, string processing, etc. Without it, this is what happens when attempting to
print the contents of a Student object.
from Student import Student
student = Student(...)
print(student)
produces
<student.Student object at 0x023C74B0>
After defining the __str__ method as:
def __str__(self):
"""
-------------------------------------------------------
Returns a string version of a student in the format
id
surname, forename
gender, birthdate
Use: print(student)
Use: print( "{}".format(student))
Use: string = str(student)
-------------------------------------------------------
Returns:
string - a formatted version of the student data (str)
-------------------------------------------------------
"""
string = """{}
{}, {}
{}, {}""".format(self.student_id, self.surname,
Unlock document

This preview shows half of the first page of the document.
Unlock all 2 pages and 3 million more documents.

Already have an account? Log in

Document Summary

The student class contains a number of other methods, some of which have special meanings in python. Python identifies special methods by surrounding their names with double underscores, as we have already seen with the __init__ constructor method. These special methods are not called by their names, but instead are called using familiar python functions or operators. The __init__ constructor, for example, is never called by the name __init__, but rather by simply using the name of the class as the constructor call. When defined in a class, the __str__ method returns a string version of the attributes of an object. This string can be used anywhere that a python string can be used - in printing, concatenation, string processing, etc. Without it, this is what happens when attempting to print the contents of a student object. from student import student student = student() print(student) produces. After defining the __str__ method as: def __str__(self):