Find the below codes and use it to build your personal diary and even further update it.
The above code, or aforementioned, seems to be accurate, precise, and, above all, correct, and should run without any errors. It correctly also creates a Diary class, adds two entries to the entire diary and then issuing of the prints-out command for the entries.
Breaking of the above codes step by step
Class Definition
‘class Diary:’
This class defines a new class which is known as ‘Diary’. A class is a blueprint for creating objects that contain data and functions that operates on that same data.
Initialization Method:
‘def __init__(self):’
This method is known as a special feature and a method in Python programming. In addition, it is also called the constructor or the initialization method. This is pulled when an object is created from the class. The self command, also is known to be a reference to the current instance of the class.
Initialization Code
The code ‘self.entries = [ ]’
Meanwhile, inside the ‘__init__’ methoed, we initializeds an empty list called ‘entries’. This list will store the diary entries depending on the number of time an entry is made.
Add Entry Method
This method allows users to add a new entry to the diary. In addition, it takes wo parameters, that is ‘self’(that is a reference to the current instance of the class) and also or however, the ‘entry’ that is the new diary entry).
Adding Entry Method ‘self.entries.append(entry)’
This method in programming is also
The add entry method that is ‘self.entries.append(entry)’ Inside the add_entry method, we append the new ‘entry’ to the ‘entries’ list using the ‘append’ method or command.
View Entries Method (‘def view_entries(self):’
This method is used to display all the diary entries.
Enumerating Entries
‘for I, entry in enumerate(self.entries, 1):’
In this context, we use ‘enumerate’ function to iterate over the ‘entries’ list. The ‘enumerate’ function in addition also returns an iterator that produces tuples containing the index ‘1’ argument which specifies that we want the index from or beginning from 1 instead of 0.
Printing Entries
‘print(f”Entry {i}: {entry}”)’
Inside the loop, we print each entry using an f-string(a formatted string literal). In addition, the f-String includes the entry number ‘i’ and therefore the entry text as ‘entry’
Creating a Diary Project
We happen to create a new object called ‘diary = Diary( )’
Adding Entries:
‘diary.add_entry(“Today was a great day! I learned a lot about python.”)’ and ‘diary.add_entry(“I’m starting to get the hang of lists and cunctions.”)’
In this case, we add two diary entries using the ‘add_entry’ method
Viewing Entries
‘diary.view_entries( )’
In conclusion, we call the ‘view_entries’ method to display all the diary entries. Right after the code is run, we should be having something precisely and similar to the below image.
About Author
Discover more from SURFCLOUD TECHNOLOGY
Subscribe to get the latest posts sent to your email.