Python Flashcards
What is MRO?
Method Resolution Order - the order in which base classes are searched when looking for a method or an attribute. In Python the MRO for most cases is depth first then left to right and remove all duplicates except the last one.
What is the output?
class First(object):
def __init__(self):
super(First, self).__init__()
print(“first”)
class Second(object):
def __init__(self):
super(Second, self).__init__()
print(“second”)
class Third(First, Second):
def __init__(self):
super(Third, self).__init__()
print(“third”)
second
first
third
What are the steps in creating an instance of a class?
Python calls its __new__ method to create the object then calls __init__ on the object that is returned. The __new__ looks like this:
def __new__(cls):
return super().__new__(cls)
If new returns an inst of a diff class, then __init__ is not called
What should init return?
None, anything else will throw an error
Add unit property to immutable built-in float.
class MyFloat(float):
def __new__(cls, value, unit):
instance = super().__new__(cls, value)
## customize here
instance.unit = unit
## return instance
return instance
## in immutable types value is set in __new__, so overwriting __init__ with unit would cause error
What are 2 ways to create a singleton?
- Module level constant
- overwrite __new__ (__init__ won’t get called)
What is variable casting?
A cast is a way of explicitly informing the compiler that you intend to make the conversion and that you are aware that data loss might occur, or the cast may fail at run time.
Python is … typed language
dynamically
n = 300
id(n) == ?
returns location of the int object 300 in memory
What is small integer caching?
small integer in python is -5 to 256
At startup of the interpreter session, python creates objects for all small integers. This is done to improve performance (because these objects are used so much)
What is the first class O?
a first-class citizen (also type, object, entity, or value) in a given programming language is an entity which supports all the operations generally available to other entities. These operations typically include being passed as an argument, returned from a function, and assigned to a variable.
What is introspection?
The ability to determine the type of an O at runtime.
What is callable? Which types are callable in Python.
Callable is a type that can be executed. Functions and classes are callable in Python.
What is LEGB rule?
When resolving a name, python looks in 1. local scope, 2. in enclosing function, 3. in global scope, 4. in built-in scope
What are decorators can be used for?
- Prevent duplication of code
Timing how long a function runs - Setting the frequency of a function run
- Memoization - caching of function results, so they don’t have to be called again (ex. 2+2 will always be 4)
- Setting an attribute for multiple unrelated classes without using inheritance.
- Register function as a plugin
What is Big O. What is the best complexity.
A notation used to describe the computational complexity of an algorithm, consists of 2 parts: time and space
the best complexity is O(1)
O stands for order of approximation
What is the difference between integration and acceptance testing?
acceptance testing is performed in the environment that is as close to production as possible
What is the diff between VM and container?
A container is a software code package containing an application’s code, its libraries, and other dependencies. Containerization makes your applications portable so that the same code can run on any device. A virtual machine is a digital copy of a physical machine.
Why can’t a python class have methods with duplicate names?
All attributes are stored in __dict__ and dictionaries cannot have duplicate keys - hence no overloading.
Is this allowed:
def add_item(x, sum=1, y):
pass
No, default params cannot be followed by regular params
Which data types are mutable in Python?
- Lists
- Dicts
- Sets
- All custom objects
- byte array (can be used as a mutable str)
Collections internally keep references to all their individual values. This opens the opportunity for mutability.
Can mutable types be used as default parameters?
Technically, yes, but it shouldn’t be done.
When you call a function with a mutable object as an argument, the function may perform mutations on that object. These mutations will affect the original object outside the function.
def add_item(item, quantity, shopping_list={}):
shopping_list[item] = quantity # next time the function is called with default param, the shopping list will not be empty - it will contain the item
What are the immutable data types?
Cannot be modified after creation. Use up a lot of memory. Helpful for multi-threading - no risk of conflict.
1. str
2. typle
3. frozen set
4. Single-item data types, such as integers, floats, complex numbers, and Booleans, are always immutable. So, you have no way to change the value of these types. You just have the option of creating a new object with a new value and throwing away the old one.
Given a tuple:
t = (1, [‘a’, ‘b’, ‘c’], “two”], “two”)
which on of these produces an error:
1. t[0] = 2
2. t[1][0] = ‘w’
3. t[2][0] = ‘w’
- TypeError - tuple o doesn’t support item assignment
- OK - list is mutable (immutability in python is not transitive)
- TypeError - str O doesn’t support item assignment
What are the 3 fundamental characteristics on a python O?
- Value
- Identity (location in memory - read only, cannot be changed)
- Type
What is a mutable object?
if you can change the value of that object without changing the object’s identity, then you have a mutable object.
What is in-place algorithm?
Transforming the content of a given data structure by operating on the data structure itself and without using or creating any auxiliary similar data structure.
Write code for creating a mutable string.
greeting = “Hello!”
mutable_greeting = bytearray(greeting.encode(“utf-8”))
mutable_greeting[1] = ord(“E”)
What is the difference between nonlocal and global?
Global is used to access and modify global variables from within a function, while nonlocal is used to access and modify variables from the nearest enclosing scope that is not global.
What is a mapping?
A mapping is a data type that has paired values as items, such as a dictionary.
What is the difference between * and ** unpacking operators.
- unpacks any iterables
** - unpacks mappings
- unpacks any iterables
The output?
my_list = [1, 2, 3, 4, 5, 6]
a, *b, c = my_list
print(a)
print(b)
print(c)
1
[2, 3, 4, 5]
6
Merge 2 lists using the unpacking operator:
my_first_list = [1, 2, 3]
my_second_list = [4, 5, 6]
my_merged_list = [*my_first_list, *my_second_list]
merge 2 dicts using unpacking operator
my_first_dict = {“A”: 1, “B”: 2}
my_second_dict = {“C”: 3, “D”: 4}
my_merged_dict = {**my_first_dict, **my_second_dict}
Whats the output of
x = range(3, 10, 2)
for n in x:
print(n)
3
5
7
9
what does the idiom if __name__ == “__main__” do?
It Allows You to Execute Code When the File Runs as a Script, but Not When It’s Imported as a Module
Explain different method types in Python.
- instance method -> can modify both class and instance state
def some_method(self):
… - class method -> can modify class state, but has no access to self
@classmethod
def some_method(cls):
… - static method -> no access to self or cls
@staticmethod
def _some_method(x):
…
Give example of @classmethod use
can be used to simplify initialization of different instance types
class Pizza:
def __init__(self, ingredients):
self.ingredients = ingredients
@classmethod
def make_margherita(cls):
return cls([tomato, cheese])
Give example of @staticmethod use
For round objects, could be used to return circle area:
class Pizza:
@staticmethod
def _circle_area(r):
return r ** 2 * math.pi
What is a package?
A collection of modules
What is Conda?
A tool for creating virtual env - part of Anaconda virtual env
What is a namespace?
collection of currently defined symbolic names along with information about the object that each name references.
What is scope?
the region of a program in which variable name has meaning.
2 ways to create branch in git
- git branch <banrch-name></banrch-name>
- git checkout -b <branch-name></branch-name>