21.11. Creating Classes¶
Look the code below. It defines a class. it also declares methods which are
functions that are defined inside of a class.
One of the methods, __init__
, is automatically called when a new object is
created by the class. One of the methods, __str__
, is automatically
called when you print an object of the class. These methods start and end with two underscores.
21.11.1. A Book Class¶
Run the following code
21.11.2. Creating More Objects¶
Once you have defined a class you can use it to create many objects.
Change the following main function to add a new person object.
21.11.3. Add a Method to a Class¶
You can add a new method to a class by adding a new function inside the class. For example, you can add the initials
method to the Person class. The name of the function
doesn’t need to have any underscores in it. It only needs to start and end with double
underscores if it is a special method like __init__
or __str__
. It does need to take
the current object which is by convention referred to as self
.
The following Person class has an initials
method that returns
a string with the first letter in the first name and the first letter in
the last name in lowercase.
21.11.4. Feedback¶
Please provide feedback here. Please share any comments, problems, or suggestions.
21.11.5. What to do next¶
Click on the following link to take the pre survey : Pre Survey