Misc Python Stuff Flashcards
How do you inspect the size of Python objects, in bytes?
import sys sys.getsizeof(object)
What’s a quick way to reverse a string?
my_string[::-1]
What are Abstract Base Classes (ABCs)?
abc is a builtin module, we have to import ABC and abstractmethod
‘Template’ classes that, when inherited by a class, specify methods and attributes that need to be implemented by that class. E.g.
~~~
from abc import ABC, abstractmethod
class Animal(ABC): # Inherit from ABC(Abstract base class)
@abstractmethod # Decorator to define an abstract method
def feed(self):
pass
class Lion(Animal):
def feed(self):
print(“Feeding a lion with raw meat!”)
~~~
T/F: Can ABCs be instantiated?
False, they can only be inherited by other classes, not instantiated
Write the equation that Python uses to find modulus
modulus = value - math.floor(value / base) * base
i.e. subtract the value from the closest lesser value where the base divides evenly
Write a test that assures a KeyError is raised when trying to access a non-existent key-value pair in a dictionary
def test_should_raise_error_on_missing_key(): my_dict = dict() with pytest.raises(KeyError) as exception_info: my_dict["missing_key"] assert exception_info.value.args[0] == "missing_key"
When building a class, what order should the static/class methods, public methods, and private methods be presented visually?
- Static/class methods
- Public methods
- Private methods
What is defensive copying, and why is it used when building classes?
Defensive copies are shallow copies of the data within the data class presented to the user in place of the actual data. This prevents intentional/unintentional manipulation of the actual data in ways that isn’t allowed within the data structure functionality.
What is white-box testing?
Testing the internal implementation of your code, instead of the public interface
What does !r
do in f-string interpolation?
It will return the repr()
object instead of the string object, giving a more explicit representation
What is the purpose of @property
when creating a class?
What is the purpose of @classmethod
when creating a class?
How do you get the name of the class from the class’s self
?
cls = self.\_\_class\_\_.\_\_name\_\_