Python Flashcards

1
Q

What is MRO?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

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”)

A

second
first
third

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What are the steps in creating an instance of a class?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What should init return?

A

None, anything else will throw an error

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Add unit property to immutable built-in float.

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What are 2 ways to create a singleton?

A
  1. Module level constant
  2. overwrite __new__ (__init__ won’t get called)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is variable casting?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Python is … typed language

A

dynamically

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

n = 300
id(n) == ?

A

returns location of the int object 300 in memory

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is small integer caching?

A

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)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is the first class O?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is introspection?

A

The ability to determine the type of an O at runtime.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is callable? Which types are callable in Python.

A

Callable is a type that can be executed. Functions and classes are callable in Python.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is LEGB rule?

A

When resolving a name, python looks in 1. local scope, 2. in enclosing function, 3. in global scope, 4. in built-in scope

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What are decorators can be used for?

A
  1. Prevent duplication of code
    Timing how long a function runs
  2. Setting the frequency of a function run
  3. Memoization - caching of function results, so they don’t have to be called again (ex. 2+2 will always be 4)
  4. Setting an attribute for multiple unrelated classes without using inheritance.
  5. Register function as a plugin
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is Big O. What is the best complexity.

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What is the difference between integration and acceptance testing?

A

acceptance testing is performed in the environment that is as close to production as possible

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What is the diff between VM and container?

A

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.

19
Q

Why can’t a python class have methods with duplicate names?

A

All attributes are stored in __dict__ and dictionaries cannot have duplicate keys - hence no overloading.

20
Q

Is this allowed:
def add_item(x, sum=1, y):
pass

A

No, default params cannot be followed by regular params

21
Q

Which data types are mutable in Python?

A
  1. Lists
  2. Dicts
  3. Sets
  4. All custom objects
  5. byte array (can be used as a mutable str)
    Collections internally keep references to all their individual values. This opens the opportunity for mutability.
22
Q

Can mutable types be used as default parameters?

A

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

23
Q

What are the immutable data types?

A

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.

24
Q

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’

A
  1. TypeError - tuple o doesn’t support item assignment
  2. OK - list is mutable (immutability in python is not transitive)
  3. TypeError - str O doesn’t support item assignment
25
Q

What are the 3 fundamental characteristics on a python O?

A
  1. Value
  2. Identity (location in memory - read only, cannot be changed)
  3. Type
26
Q

What is a mutable object?

A

if you can change the value of that object without changing the object’s identity, then you have a mutable object.

27
Q

What is in-place algorithm?

A

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.

28
Q

Write code for creating a mutable string.

A

greeting = “Hello!”
mutable_greeting = bytearray(greeting.encode(“utf-8”))
mutable_greeting[1] = ord(“E”)

29
Q

What is the difference between nonlocal and global?

A

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.

30
Q

What is a mapping?

A

A mapping is a data type that has paired values as items, such as a dictionary.

31
Q

What is the difference between * and ** unpacking operators.

A
    • unpacks any iterables
      ** - unpacks mappings
32
Q

The output?
my_list = [1, 2, 3, 4, 5, 6]

a, *b, c = my_list

print(a)
print(b)
print(c)

A

1
[2, 3, 4, 5]
6

33
Q

Merge 2 lists using the unpacking operator:
my_first_list = [1, 2, 3]
my_second_list = [4, 5, 6]

A

my_merged_list = [*my_first_list, *my_second_list]

34
Q

merge 2 dicts using unpacking operator
my_first_dict = {“A”: 1, “B”: 2}
my_second_dict = {“C”: 3, “D”: 4}

A

my_merged_dict = {**my_first_dict, **my_second_dict}

35
Q

Whats the output of
x = range(3, 10, 2)
for n in x:
print(n)

A

3
5
7
9

36
Q

what does the idiom if __name__ == “__main__” do?

A

It Allows You to Execute Code When the File Runs as a Script, but Not When It’s Imported as a Module

37
Q

Explain different method types in Python.

A
  1. instance method -> can modify both class and instance state
    def some_method(self):
  2. class method -> can modify class state, but has no access to self
    @classmethod
    def some_method(cls):
  3. static method -> no access to self or cls
    @staticmethod
    def _some_method(x):
38
Q

Give example of @classmethod use

A

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])

39
Q

Give example of @staticmethod use

A

For round objects, could be used to return circle area:
class Pizza:
@staticmethod
def _circle_area(r):
return r ** 2 * math.pi

40
Q

What is a package?

A

A collection of modules

41
Q

What is Conda?

A

A tool for creating virtual env - part of Anaconda virtual env

42
Q

What is a namespace?

A

collection of currently defined symbolic names along with information about the object that each name references.

43
Q

What is scope?

A

the region of a program in which variable name has meaning.

44
Q

2 ways to create branch in git

A
  1. git branch <banrch-name></banrch-name>
  2. git checkout -b <branch-name></branch-name>