Python questions Flashcards
(69 cards)
List vs Tuple
List:
- Mutable
- Worse performance
- More built-in methods
Tuple:
- Immutable
- Better performance (faster iterations, less memory used)
- Less built-in methods
What is __init__() ?
It is a method which is class constructor
What is list comprehension?
It’s a loop statement condensed to one line, usually used to create a new, altered list based on other list eg:
odd_powers_of_two = [2**x for x in range(0, 11) if ( x % 2 ) == 1]
Are python classess fully mutable?
Yes, to the point of programmer being able to replace classess methods during runtime of the program (monkeypatching)
Exceptions - full statement
class XdError(Exception):
pass
try:
raise XdError
1/”xd”
except ZeroDivisionError:
print(“Nie dziel przez zero”)
except TypeError:
print(“Nie dziel przez c”)
except XdError:
print(“Nie dziel przez xd”)
except:
print (“other exception”)
else:
print (“else”)
finally:
print (“finally”)
What is decorator?
Decorator is a function which can modify behavior of other function (creates and returns other function, which adds some behavior around the base function)
How to use decorator function without @decorator statement?
def example_decorator ( func ):
def wrapper(args, **kwargs):
print(“Decorator Start”)
result = func(args, **kwargs)
print(“Decorator End”)
return result return wrapper
def print_xd():
print(“xd”)
print_xd = example_decorator ( print_xd )
print_xd()
What is del keyword used for?
del is used to delete objects; everything in Python is an object, so everything can be deleted
Create class with one private attribute; create getter and setter to the attribute
class Person:
def \_\_init\_\_(self, name: str) -> None: self._name: str = name @property def name(self): return self._name @name.setter def name(self, new_name): self._name = new_name
p1 = Person(“Anna”)
print(p1.name)
p1.name = “Janina”
print(p1.name)
What is set?
set - unordered collection of unique items (items can be added or popped, but not changed)
What is *args?
args is a dictionary
It’s argument for unknown number of arguments in function:
def example(*args):
#args is a tuple
for word in args:
print(word)
What is @staticmethod
It is a decorator for creating a static method, which means that the method can be called by refering both to class and instance of the class:
class Class:
@staticmethod
def static_method(a, b):
…
both are ok:
Class.static_method(1, 2)
Class().static_method(1,2)
What is a dictionary?
It’s an ordered (since Py3.7), changeable, unique* collection of pairs key:value
- only keys need to be unique
What is @classmethod
It is a decorator allowing for creation of function, refering to class, not to instance of it:
class Class
@classmethod
def class_method(cls):
…
What is **kwargs
It’s argument for unknown number of keyworded arguments in function:
def example(**kwargs):
#kwargs is a dictionary
for key, value in kwargs.items():
print(f”{key}: {value}”)
What are hashing algorithms used for?
They are used for creating signatures for messages and files in order to assure they haven’t been changed e.g. during transmission
What are examples of hashing algorithms?
MD-5
SHA-1
SHA-256
When to use THREADS ?
For concurrent tasks, which need to syncronise access to data
When to use ASYNCIO ?
For tasks with waiting times, which can be carried out concurrently, but without need to share data
When to use PROCESSES ?
When performance is the key; when you need to run and syncronise multiple applications
Using asyncio make concurrent program
import asyncio
async def fetch_data(time_s):
await asyncio.sleep(time_s)
print(f”Awaited: {time_s} seconds”)
async def main():
print(“start main”)
task1 = asyncio.create_task(fetch_data(3)) task2 = asyncio.create_task(fetch_data(1)) await task1 await task2 task3 = asyncio.create_task(fetch_data(2)) await task3 print("end main")
asyncio.run(main())
What is lambda?
it’s one line, anonymous function:
x = lambda a, b : a+b
What is with statement used for?
It’sa context manager used for exception management in cases like openeing files - it guards access to resources, which should not be access after end of with block
Name 4 Python namespaces
Built-in
Global
Enclosed
Local