To create a class, use the keyword class followed by the class name and a colon. In Python, class names follow the CapWords naming convention where each word in the name is capitalized with no underscores.
class ClassName:
We will need to create an object, and when we do, we want to give an initial value to all of its attributes. In other words, we want to initialize all of its attributes. To do that, we define a constructor, which is always named __init__().
For example, suppose you wanted a student to have the attributes:
first_name
last_name
grade_level (9, 10, etc.)
is_enrolled (whether or not they are currently enrolled)
grade_list (a list of their current grades)
Here is one way you could write the constructor:
class Student:
def __init__(self, first_name, last_name, grade_level):
self.first_name = first_name
self.last_name = last_name
self.grade_level = grade_level
self.is_enrolled = True
self.grade_list = []
When this student is constructed, you must give a first_name, last_name, and grade_level as arguments, and those will be assigned to the student.
The attribute is_enrolled is set to True, and the attribute grade_list is set to an empty list.
We mentioned before that attributes will always be attached to an object, but often inside a class we don't yet know the name of the object we'll be acting on, so we give this object a placeholder name. This placeholder name must be the first parameter in all instance methods but will not be given an argument (at least in the typical way) when the method is called.
By convention, we use self as the placeholder name for the object. This is not a keyword, but breaking convention just adds confusion and makes your code harder to read.
Now you can add methods that can act on the objects you create. Again, these methods will all have self as the first parameter.
Note that any changes you make to the attributes of an object within a method will permanently change that object everywhere in your subsequent code.
Here is a method to move a Student to the next grade.
def promote(self):
self.grade_level += 1
This method will return the student's grade average.
def get_average(self):
return sum(self.grade_list)/len(self.grade_list)
This method will add a grade to the student's grade list.
def add_grade(self, grade):
self.grade_list.append(grade)
It is very helpful to be able to print or have a string representation of our objects. But if you print a Student object, you will get output like this:
<__main__.Student object at 0x7ff6bb48b730>
This usually isn't helpful, so it's nice to override the str() function. To do this, we write a method with the name __str__() that returns a more useful string for printing and other applications.
For example:
def __str__(self):
return self.first_name + " " + self.last_name
Now printing a Student object will just print the Student's full name.