python Flashcards

1
Q

What is the purpose of the function super() in the subclass?

A

we can access the parent’s class properties and methods when building the subclass

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

explain a lambda function in python

A

A lambda function in Python is a small anonymous function defined using the lambda keyword, typically used for simple operations and as arguments in higher-order functions.

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

explain a map function in python

A

The map() function in Python applies a given function to each item of an iterable (such as a list) and returns a new iterable containing the results.

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

Explain a tuple in python

A

In Python, a tuple is an immutable, ordered collection of elements enclosed within parentheses, allowing for the storage of multiple items which can be of different data types, accessed by indexing, and used as keys in dictionaries or elements in sets.

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

What is the difference between / and // in Python

A

/ represents precise division (result is a floating point number) whereas // represents floor division (result is an integer).
5//2 = 2
5/2 = 2.5

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

What are *args and *kwargs?

A

To pass a variable number of arguments to a function in Python, use the special syntax *args and **kwargs in the function specification. It is used to pass a variable-length, keyword-free argument list. By using the *, the variable we associate with the * becomes iterable, allowing you to do operations on it such as iterating over it and using higher-order operations like map and filter.

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

Does Python supports multiple Inheritance?

A

Python does support multiple inheritances, unlike Java. Multiple inheritances mean that a class can be derived from more than one parent class.

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

What is Polymorphism in Python?

A

Polymorphism means the ability to take multiple forms. So, for instance, if the parent class has a method named ABC then the child class also can have a method with the same name ABC having its own parameters and variables. Python allows polymorphism.

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

Define encapsulation in Python?

A

Encapsulation means binding the code and the data together. A Python class is an example of encapsulation.

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

What is slicing in Python?

A

Python Slicing is a string operation for extracting a part of the string, or some part of a list. With this operator, one can specify where to start the slicing, where to end, and specify the step. List slicing returns a new list from the existing list.

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

What is a zip function?

A

ython zip() function returns a zip object, which maps a similar index of multiple containers. It takes an iterable, converts it into an iterator and aggregates the elements based on iterables passed. It returns an iterator of tuples.

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

What are Pickling and Unpickling?

A

The Pickle module accepts any Python object and converts it into a string representation and dumps it into a file by using the dump function, this process is called pickling. While the process of retrieving original Python objects from the stored string representation is called unpickling.

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

What is monkey patching in Python?

A

the term monkey patch only refers to dynamic modifications of a class or module at run-time.

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

What is __init__() in Python?

A

Equivalent to constructors in OOP terminology, __init__ is a reserved method in Python classes. The __init__ method is called automatically whenever a new object is initiated. This method allocates memory to the new object as soon as it is created. This method can also be used to initialize variables.

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

What are Access Specifiers in Python?

A

Python uses the ‘_’ symbol to determine the access control for a specific data member or a member function of a class. A Class in Python has three types of Python access modifiers:

Public Access Modifier: The members of a class that are declared public are easily accessible from any part of the program. All data members and member functions of a class are public by default.
Protected Access Modifier: The members of a class that are declared protected are only accessible to a class derived from it. All data members of a class are declared protected by adding a single underscore ‘_’ symbol before the data members of that class.
Private Access Modifier: The members of a class that are declared private are accessible within the class only, the private access modifier is the most secure access modifier. Data members of a class are declared private by adding a double underscore ‘__’ symbol before the data member of that class.

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

Describe how inheritance allows a class to inherit properties and methods from another class. Explain the super() function and demonstrate how to create subclasses and access parent class methods and attributes

A

Inheritance in Python is a mechanism where a class (subclass or derived class) inherits attributes and methods from another class (base class or parent class). It promotes code reusability and hierarchical organization. To use inheritance, you can create a subclass that inherits from a parent class using the following syntax:

class Parent:
def __init__(self, name):
self.name = name

class Child(Parent):
def __init__(self, name, age):
super().__init__(name) # Call the parent class constructor
self.age = age
In this example, the Child class inherits the name attribute from the Parent class and adds its own age attribute.

17
Q

What is method overriding in Python?

A

Method overriding in Python occurs when a subclass provides its own implementation of a method that is already defined in its parent class. This allows the subclass to customize the behavior of that method without changing its name or parameters. To override a method, you need to define a method in the subclass with the same name and parameters as the method in the parent class. Here’s an example:

class Parent:
def greet(self):
print(“Hello from Parent”)

class Child(Parent):
def greet(self):
print(“Hello from Child”)

child = Child()
child.greet() # This will call the greet method in the Child class.
In this example, the Child class overrides the greet method inherited from the Parent class.

18
Q

What is a decorator in Python, and how is it used?

A

In Python, a decorator is a function that takes another function as an argument and extends or modifies its behavior without changing its source code. Decorators are often used to add functionality such as logging, authentication, or memoization to functions or methods.

Here’s an example of a simple decorator:

def my_decorator(func):
def wrapper():
print(“Something is happening before the function is called.”)
func()
print(“Something is happening after the function is called.”)
return wrapper

@my_decorator
def say_hello():
print(“Hello!”)

say_hello()
In this example, the my_decorator function is used as a decorator to modify the behavior of the say_hello function.

19
Q

Explain the difference between map(), filter(), and reduce() functions in Python.

A

map(), filter(), and reduce() are three important functions in Python for working with iterables.

map(): The map() function applies a given function to each item in an iterable (e.g., a list) and returns a new iterable with the results. For example:
numbers = [1, 2, 3, 4, 5]
squared = map(lambda x: x**2, numbers)
filter(): The filter() function filters elements from an iterable based on a given condition, returning a new iterable containing only the elements that satisfy the condition. For example:
numbers = [1, 2, 3, 4, 5]
even_numbers = filter(lambda x: x % 2 == 0, numbers)
reduce(): The reduce() function from the functools module continuously applies a binary function to the elements of an iterable, reducing it to a single value. For example:
from functools import reduce
numbers = [1, 2, 3, 4, 5]
sum_of_numbers = reduce(lambda x, y: x + y, numbers)

20
Q

What is the Global Interpreter Lock (GIL) in Python, and how does it impact multithreading?

A

Explain the Global Interpreter Lock (GIL) as a mutex that allows only one thread to execute Python bytecode at a time. Discuss its impact on multithreading and its implications for CPU-bound and I/O-bound tasks.

21
Q

Explain how memory management works in Python, including garbage collection.

A

In Python, memory management is primarily based on reference counting and a cyclic garbage collector.

Reference Counting: Python keeps track of the number of references to each object. When an object’s reference count drops to zero (i.e., there are no more references to it), Python’s memory manager deallocates the memory used by the object immediately.
Garbage Collector: Python also has a cyclic garbage collector that identifies and collects cyclic references, which are references between objects that form a cycle and cannot be freed by reference counting alone. The garbage collector detects these cycles and reclaims memory occupied by objects in such cycles.
For example, consider two objects A and B, where A references B, and B references A. Without a garbage collector, these objects would never be deleted because their reference counts would never drop to zero. The cyclic garbage collector identifies and resolves such situations.

22
Q

How can you connect to a relational database in Python, and what libraries can you use for database access?

A

o connect to a relational database in Python, you can follow these general steps:

Import the appropriate database library:
import sqlite3 # for SQLite
import MySQLdb # for MySQL
import psycopg2 # for PostgreSQL
Establish a connection to the database by providing connection parameters:
conn = sqlite3.connect(‘mydb.db’) # Example for SQLite
conn = MySQLdb.connect(host=’localhost’, user=’user’, password=’password’, database=’mydb’) # Example for MySQL
conn = psycopg2.connect(host=’localhost’, user=’user’, password=’password’, database=’mydb’) # Example for PostgreSQL
Create a cursor object to interact with the database:
cursor = conn.cursor()
Execute SQL queries using the cursor and fetch results as needed:
cursor.execute(“SELECT * FROM mytable”)
rows = cursor.fetchall()
Close the cursor and the database connection when finished:
cursor.close()
conn.close()
Popular libraries for database access in Python include sqlite3 (for SQLite), MySQLdb (for MySQL), psycopg2 (for PostgreSQL), and SQLAlchemy (which supports multiple database systems). The choice of library depends on the specific database system you’re working with and your project requirements

23
Q

What is SQL injection, and how can it be prevented in Python applications?

A

SQL injection is a security vulnerability in which an attacker injects malicious SQL code into input fields of a web application or database query. This can lead to unauthorized access, data leakage, or data manipulation. Here’s an example of a vulnerable query:

user_input = “’; DROP TABLE users; –”
query = f”SELECT * FROM products WHERE name = ‘{user_input}’”
To prevent SQL injection in Python applications, follow these best practices:

Use Parameterized Queries: Instead of directly embedding user input in SQL queries, use parameterized queries or prepared statements provided by database libraries. For example, using sqlite3:
user_input = “’; DROP TABLE users; –”
cursor.execute(“SELECT * FROM products WHERE name = ?”, (user_input,))

Use Object-Relational Mapping (ORM) Frameworks: ORM frameworks like SQLAlchemy or Django’s ORM automatically handle query parameterization and protect against SQL injection.
Input Validation: Validate and sanitize user inputs to ensure they match expected patterns and do not contain harmful SQL code.
Escaping User Input: If you can’t use parameterized queries, escape user input before embedding it in SQL queries. Most database libraries provide methods for escaping.