Saturday Afternoon Python
Saturday Afternoon Python
Last night I went to the best dance class of my life. We danced for two hours which is the usual duration of such classes. But it was something else. There was something truly special about it. The fairy lights made the room so beautiful. And the playlist was absolutely magical. I would rather be chilling. I really would rather. But I need to get a bit of Python done.
UserDict
This lets us define our own type of dictionary.
You can use it when you want to add extra behaviour to the dictionary.
UserList
This also allows to create our own version of a list. How interesting. I wonder what could that be? It says that it has a property called "data" that allows us to access list contents directly. Huh. Hmmmmmmm.
We can also overwrite methods from the list class.
When you create a new instance of a UserList, it uses an internal attribute called 'data' to hold the list of the actual items.
Okay this is actually so cool - I wrote some really neat code in my lesson:
from collections import UserList
data = [4, 6, 8, 9, 5, 7, 3, 1, 0]
# Write your code below!
class ListSorter(UserList):
def append(self, item):
self.data.append(item)
self.data.sort()
sorted_list = ListSorter(data)
sorted_list.append(2)
print(sorted_list)
This is soooo neat I love it so much it allows you to sort and append the code at the same time. It is soooooo cool. What a cool function.
UserString
I am losing the will slowly, sorry. It is the weekend. I am all danced out. I made 28 handmade Christmas cards today and I am not done.
After Christmas I will calm down.
Strings are also considered to be containers too.
So the collections module provides some stuff for them as well. Wrote some nice neat code here too.
Here we go:
from collections import UserString
str_name = 'python powered patterned products'
str_word = 'patterned '
# Write your code below!
class SubtractString(UserString):
def __sub__(self, other):
if other in self.data:
self.data = self.data.replace(other,'')
subtract_string = SubtractString(str_name)
subtract_string - str_word
print(subtract_string)
Quiz
Well I did okay. It was a super hard one.
And I had to wrestle with it a bit!
Thank you
Comments
Post a Comment