Python Flashcards
(13 cards)
What is a dunder method?
A special method or magic method, internal to python framework objects that begin and end with a double underscore:
collection.__getitem__(key)
This is the dunder method getitem.
What is a namedtuple?
A class of object that is a bundle of attributes with no custom methods, like a database record.
Card = collections.namedtuple(‘Card’, [‘rank’,’suit’])
Which module contains namedtuple?
collections
How do you make a class respond to the len() function?
Implement the __len__ dunder method:
def __len__(self):
How do you make a class indexable (my_class[0])?
Implement the __getitem__ dunder method:
def __getitem__(self, position):
How do you get a random item from a sequence?
Use the choice method in the random module:
from random import choice
choice( sequence )
What dunder method returns the string representation of an object?
def __repr__(self):
If you can only implement __repr__ or __str__ which one would you implement and why?
You would implement __repr__, because if there is no custom __str__ available Python will call __repr__ as a fallback.
What should the output of __repr__ be?
The output should be unambiguous and, if possible, match the source code necessary to re-create the object being represented.
What is the difference between the types of things contained by a container sequence and a flat sequence?
A container sequence contains references to the objects within. A flat sequence physically stores the value of each item within its own memory space and not as distinct objects.
Flat sequences are more compact, but limited to holding primitives such as characters, bytes, and numbers.
What is a list comprehension for producing a cartesian product of two lists?
[(x,y) for x in list1 for y in list2]
What is the main difference in memory utilization between a list comprehension and a generator expression?
A list comprehension generates a complete list in memory. A generator expression generates elements one at a time (so has better memory performance in a for loop, for example).
How to reverse a string s?
’‘.join(reversed(s))