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.

A Book Class

Run the following code

Before you keep reading...

Making great stuff takes time and $$. If you appreciate the book you are reading now and want to keep quality materials free for other students please consider a donation to Runestone Academy. We ask that you consider a $10 donation, but if you can give more thats great, if $10 is too much for your budget we would be happy with whatever you can afford as a show of support.

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 person object with your first and last name.

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 function must take an object of the class to work with that by convention we call self. The name of the function doesn’t need to have any underscores in it.

Change the following Person class to add 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.

Feedback

Q-4: Please provide feedback here. Please share any comments, problems, or suggestions.

What to do next

Click on the following link to go the practice problems: Practice Problems

You have attempted 1 of 5 activities on this page