linkedin-skill-assessments-quizzes

Python (Langage de Programmation)

Note: Ceci est une traduction française du quiz d’évaluation des compétences Python de LinkedIn. Pour la version originale en anglais, consultez python-quiz.md.


Q1. Qu’est-ce qu’une classe abstraite ?

référence

Q2. Que se passe-t-il lorsque vous utilisez la fonction intégrée any() sur une liste ?

exemple

if any([True, False, False, False]) == True:
    print('Yes, there is True')
>>> 'Yes, there is True'

Q3. À quelle structure de données un arbre binaire dégénère-t-il s’il n’est pas correctement équilibré ?

référence

Q112. Quelle est la syntaxe correcte pour définir une méthode d’instance ?

def get_next_card():
  # corps de la méthode ici
def get_next_card(self):
  # corps de la méthode ici
def self.get_next_card():
  # corps de la méthode ici
def self.get_next_card(self):
  # corps de la méthode ici

Q113. Quelle est la syntaxe correcte pour créer une variable liée à un dictionnaire ?

référence

Q114. Quelle est la manière correcte d’appeler une fonction ?

Q115. Quelle est la manière correcte d’appeler une méthode d’instance sur une classe nommée Game ?

Reference

Q117. Ce code fournit le _ de la liste de nombres.

num_list = [21, 13, 19, 3, 11, 5, 18]
num_list.sort()
num_list[len(num_list) // 2]

Explication : // est l’opérateur de division entière, qui est une opération de division normale qui retourne le plus grand entier possible, inférieur ou égal au résultat de la division normale. Ici, il est utilisé pour trouver la médiane, qui est la valeur séparant la moitié supérieure de la moitié inférieure d’un échantillon de données, en trouvant l’index de l’élément de la liste au milieu de la liste. (Ceci est suffisant pour une liste avec un nombre impair d’éléments ; si la liste avait un nombre pair d’éléments, vous feriez la moyenne des valeurs des deux éléments du milieu pour trouver la valeur médiane.)

Q118. Quelles sont les deux principales structures de données dans la bibliothèque Pandas ?

Référence

Q119. Supposons que vous ayez une variable nommée vector de type np.array avec 10 000 éléments. Comment pouvez-vous transformer vector en une variable nommée matrix avec des dimensions 100x100 ?

Référence

Q120. Quel choix est un type de données immuable ?

Référence

Q121. Quelle est la sortie de ce code ?

def myFunction(country = "France"):
    print(f"Hello, I am from {country}")

myFunction("Spain")
myFunction("")
myFunction()
Hello, I am from Spain
Hello, I am from
Hello, I am from
Hello, I am from France
Hello, I am from France
Hello, I am from France
Hello, I am from Spain
Hello, I am from
Hello, I am from France
Hello, I am from Spain
Hello, I am from France
Hello, I am from France

Q122. Choisissez l’option ci-dessous pour laquelle une instance de la classe ne peut PAS être créée.

Référence

Q123. En utilisant Pandas, nous chargeons un ensemble de données de Kaggle, structuré comme dans l’image ci-dessous. Quelle commande retournera le nombre total de survivants ?

Q129

Explication : Le titanic['Survived'] retourne un objet pandas.Series, qui contient la colonne Survived du DataFrame. L’addition des valeurs de cette colonne (c’est-à-dire sum(titanic['Survived'])) retourne le nombre total de survivants car un survivant est représenté par un 1 et une perte par 0.

Q124. Comment créeriez-vous une liste de tuples correspondant à ces listes de personnages et d’acteurs ?

characters = ["Iron Man", "Spider Man", "Captain America"]
actors = ["Downey", "Holland", "Evans"]

# sortie exemple : [("IronMan", "Downey"), ("Spider Man", "Holland"), ("Captain America", "Evans")]

Q125. Que retournera cette instruction ?

{x : x*x for x in range(1,100)}

Q126. La similarité de Jaccard est une formule qui vous indique à quel point deux ensembles sont similaires. Elle est définie comme la cardinalité de l’intersection divisée par la cardinalité de l’union. Quel choix est une implémentation exacte en Python ?

Q132

Référence

Q127. Quel choix n’est PAS un type numérique natif en Python ?

Q128. Quelle sera la sortie de ce code ?

[1,2,3] * 3

Q129. Étant donné une liste définie comme numbers = [1,2,3,4], quelle est la valeur de numbers[-2] ?

Q130. Quelle affirmation sur les chaînes de caractères en Python est vraie ?

Q131. Quelle est la syntaxe correcte pour définir une méthode __init__() qui ne prend aucun paramètre ?

Référence

Explication : L’instruction from..import vous permet d’importer des fonctions/variables spécifiques d’un module au lieu de tout importer.

Q133. Qu’obtenez-vous si vous appliquez numpy.sum() à une liste qui ne contient que des valeurs booléennes ?

Q134. Qu’imprimera ce code ?

print("foo" if (256).bit_length() > 8 else "bar")

Q135. Si vous ne retournez pas explicitement une valeur d’une fonction, que se passe-t-il ?

Q136. Il est souvent le cas que la bibliothèque pandas est utilisée pour les données _ et NumPy pour les données _.

Explication : La bibliothèque Pandas est couramment utilisée pour travailler avec des données tabulaires, telles que des données sous forme de tableaux ou de feuilles de calcul. Elle fournit des structures de données et des fonctions pour la manipulation et l’analyse de données. D’autre part, NumPy est une bibliothèque puissante pour le calcul numérique en Python, et elle est souvent utilisée pour effectuer des opérations mathématiques sur des données numériques, telles que des tableaux et des matrices.

Q137. Que devez-vous faire pour installer des packages supplémentaires dans Python ?

Q138. L’image ci-dessous a été créée en utilisant Matplotlib. C’est un graphique de distribution d’une liste d’entiers remplis de nombres en utilisant la fonction _ et tracé avec _.

Q132

Référence

Q139. Dans ce fragment de code, quelles seront les valeurs de a et b ?

import numpy as np

a = np.arange(100)
b = a[50:60:2]

Q140. Lors de l’utilisation de NumPy en Python, comment vérifiez-vous la dimensionnalité (nombre et longueur des dimensions) d’un objet appelé my_object ?

Q141. Supposons que vous ayez une liste non vide nommée mylist et que vous souhaitiez rechercher une valeur spécifique. Le nombre minimum de comparaisons sera _ et le nombre maximum de comparaisons sera _ ?

Explication : On peut utiliser une instruction break et la valeur recherchée peut être le premier élément de la liste, étant donné qu’elle est non vide.

Q142. Si une fonction n’a pas d’instruction return, que retourne-t-elle ?

Q143. Supposons que vous souhaitiez vérifier si deux matrices peuvent être multipliées en utilisant NumPy à des fins de débogage. Comment compléteriez-vous ce fragment de code en remplissant les espaces vides avec les variables appropriées ?

import numpy as np

def can_matrices_be_multiplied (matrix1, matrix2):
    rowsMat1, columnsMat1 = matrix1.shape
    rowsMat2, columnsMat2 = matrix2.shape

    if _____ == ______ :
        print("Les matrices peuvent être multipliées !")
        return True
    else:
        return False

référence. Une matrice peut être multipliée par toute autre matrice qui a le même nombre de lignes que la première a de colonnes. Par exemple, une matrice avec 2 colonnes peut être multipliée par toute matrice avec 2 lignes

Q144. Quelle est la sortie de cette compréhension ?

[(x, x+1) for x in range(1,5)]

Q145. En Python, une méthode de classe doit avoir _ comme décorateur de fonction, et le premier paramètre de la méthode sera une référence à _.

Référence

Q146. Quel extrait de code imprimera My name is Joffrey, son of Robert ?

class Father():
    name = 'Robert'

class Person(Father):
    def __init__(self, name):
        self.fathername = super.name
        self.name = name

    def introduce(self):
        print(f"My name is {self.name} son of {self.fathername}")

king = Person("Joffrey")
king.introduce()

class Father():
    name = 'Robert'


class Person(Father):
    def __init__(self, name):
        self.fathername = self.name
        self.name = name

    def introduce(self):
        print(f"My name is {self.name} son of {self.fathername}")


king = Person("Joffrey")
king.introduce()

class Father():
    name = 'Robert'


class Person(Father):
    def __init__(self, name):
        self.name = name

    def introduce(self):
        print(f"My name is {self.name} son of {super.name}")

king = Person("Joffrey")
king.introduce()
class Father():
    name = 'Robert'

class Person(Father):
    def __init__(self, name):
        self.name = name

    def introduce(self):
        print(f"My name is {self.name} son of {base.name}")

king = Person("Joffrey")
king.introduce()

Explication : Dans le premier, super n’a pas .name (devrait être self.name). Le troisième perd Robert, et base n’est pas défini dans le 4ème.

Q147. Qu’affichera ce code dans la console, en supposant que defaultdict a déjà été importé ?

animals = {
    'a': ['ant', 'antelope', 'armadillo'],
    'b': ['beetle', 'bear', 'bat'],
    'c': ['cat', 'cougar', 'camel']
}

animals = defaultdict(list, animals)

print(animals['b'])
print(animals['d'])
      ['beetle', 'bear', 'bat']
      []
      ['beetle', 'bear', 'bat']
      # an exception will be thrown
      ['beetle', 'bear', 'bat']
      None
      ['bat', 'bear', 'beetle']
      []

Explication : Les dictionnaires entraînent généralement une exception lors de l’utilisation de la syntaxe des crochets. Defaultdict ici retourne une valeur par défaut dédiée par le premier paramètre, donc au lieu de lever une exception, ils retournent la valeur par défaut. Notez que cela doit être importé comme suit : from collections import defaultdict

Référence

Q148. Que retournera cette ligne de code ? (Supposons que n est déjà défini comme toute valeur entière positive.)

[x*2 for x in range(1,n)]

Référence

Q149. Qu’imprimera ce code dans la console ?

x = 18

if x > 10:
    if x > 15:
        print('A')
    else:
        print('B')
else:
    print('C')

Q150. Quelle est la longueur maximale d’un identifiant Python ?

référence Aucune longueur fixe n’est spécifiée mais Pep-8 spécifie sous “Longueur maximale de ligne” de “Limiter toutes les lignes à un maximum de 79 caractères”.

Q151. Quelle sera la valeur de la variable i lorsque la boucle suivante terminera son exécution ?

for i in range(5): pass

Q152. Les f-strings sont également appelées :

Q153. Combien de CPU (ou cœurs) la bibliothèque de threading Python exploitera-t-elle simultanément ?

Explication : Le threading Python est limité à un seul CPU à la fois. La bibliothèque multiprocessing vous permettra d’exécuter du code sur différents processeurs.

Q154. Quelle sera la valeur de y dans ce code ?

x = 5
y = 1 + (20 if x < 5 else 30)

Référence

Explication : Si vous n’avez qu’une seule instruction à exécuter, une pour if et une pour else, vous pouvez tout mettre sur la même ligne.

x = 5
# This is the same statement expanded to multiple lines
y = 1
if (x < 5):
    y += 20
else:
    y += 30

Q155. Le processus de pickling en Python inclut ?

référence
“Pickling” est le processus par lequel une hiérarchie d’objets Python est convertie en flux d’octets, et “unpickling” est l’opération inverse, par laquelle un flux d’octets (provenant d’un fichier binaire ou d’un objet de type bytes) est reconverti en hiérarchie d’objets.

Q156. Qu’est-ce que the output of the following program?

print("codescracker".endswith("er"))

Q157. Is the list mutable in Python?

Q158. Qu’est-ce que the output of the following program?

print("programming".center())

reference. The center() method will center align the string, using a specified character (space is the default) as the fill character.
Syntax: string.center(length, character) where length is required!

Q159. Who created the Python programming language?

Q160. Quel(le) collection is ordered, changeable, and allows duplicate members?

Q161. Que va be printed in the console if you run this code?

x = 1j
print(x**2 == -1)

Explanation: The letter j acts as the imaginary unit in Python, therefore x**2 means j**2 which is equal to -1. The statement x**2 == -1 is evaluated as True.

Q162. Que va be printed in the console if you run this code?

print(0xA + 0xB + 0xC)

Explanation: A, B and C are hexadecimal integers with values 10, 11 and 12 respectively, so the sum of A, B and C is 33.

Q163. Que va this code output to the screen?

for i in range(5):
    print(i)
else:
    print("Done!")
1
2
3
4
5
Done!
0
1
2
3
4
5
Done!
0
1
2
3
4
Done!

Q164. Quel(le) comparison of lists and tuples in Python is correct?

Reference

Q165. Consider the following code snippet that uses decorators to calculate the execution time of the execution_fn function:

import functools
import time

def timer(MISSING_ARG_1):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        start_time = time.perf_counter()
        rval = func(*args, **kwargs)
        end_time = time.perf_counter()
        duration = end_time - start_time
        print(f"Executed in {duration:.4f} seconds")
        return MISSING_ARG_2
    return MISSING_ARG_3

@timer
def execution_fn():
    for i in range(3):
        time.sleep(1)

execution_fn()

Which of the following choices are the missing arguments?

MISSING_ARG_1 = wrapper

MISSING_ARG_2 = rval

MISSING_ARG_3 = func
MISSING_ARG_1 = func

MISSING_ARG_2 = rval

MISSING_ARG_3 = wrapper
MISSING_ARG_1 is empty

MISSING_ARG_2 = rval

MISSING_ARG_3 = wrapper
MISSING_ARG_1 is empty

MISSING_ARG_2 = rval

MISSING_ARG_3 = func

Q166. Quel(le) of the following statements defines a new object type named Dog in Python?

Q167. To use pipelines in scikit-learn, import from the scikit-learn._ submodule.

reference The correct syntax is actually: from sklearn.pipeline import Pipeline

Q168. You should pass in a value of _ for the axis argument to the Pandas apply method to apply the function to each row.

Q169. Data points in Pyplot are called…

Q170. Que fait this code print?

a = np.array([[1, 2], [3, 4], [5, 6]])
c = a[(a > 3) & (a < 11)]
print(c)

Q171. Assume m, n, and p are positive integers. In the following comprehension, how many times will the function randint be called?

[ [ [ randint(1,100) for i in range(m) ] for j in range(n) ] for k in range(p) ]

Q172. Suppose you have a class named MyClass which has multiple inheritance and methods with the same name in its ancestors. Quel(le) class method could you call to see which method will get priority when invoked?

Explanation: MRO stands for Method Resolution Order. It returns a list of types the class is derived from, in the order they are searched for methods.

Q173. Suppose you have a list of employees described by the code below. You want to assign Alice the same salary as Charlie. Quel(le) choice will accomplish that?

employees = {
    'alice':{
        'position':'Lead Developer',
        'salary':1000
    },
    'bob':{
        'position': 'Lead Artist',
        'salary':2000
    },
    'charlie':{
        'position':'cfo',
        'salary':3000
    }
}

Explanation: This is accessing a key in a dictionary nested inside another dictionary. The command employees['alice']['salary'] = employees['charlie']['salary'] assigns the value of the salary key in the dictionary of the employee charlie to the value of the salary key in the dictionary of the employee alice.

Q174. You are given this piece of code. Assume m and n are already defined as some positive integer value. Quand it completes, how many tuples will my list contain?

mylist = []

for i in range(m):
    for j in range(n):
        mylist.append((i,j))

Explanation: This code will run for m x n times, if you run this code, it will create m x n tuples.

The first loop runs for m times and the inner loop will run for n times. The single iteration of the first loop will only be completed when all of the n iterations of an inner loop are completed. This is the same process for 2nd, and 3rd, … mth iterations for outer loop. Overall, both loops will run m x n times.

Q175. Que va this comprehension provide you?

{x : [y for y in range (1, x) if x % y == 0] for x in range (2, 100)}

Q176. Qu’est-ce que a common use of Python’s sys library?

Q177. Qu’est-ce que the output of 17 % 15 ?

Q178. Let the lists ‘characters’ and ‘actors’ be defined as given. Quel(le) of the following lines of code gives the desired output?

characters = ["Iron Man", "Spider Man", "Captain America"]
actors = ["Downey", "Holland", "Evans"]

#Desired output : [("Iron Man", "Downey), ("Spider Man", "Holland"), ("Captain America", "Evans")]

Explanation: zip() is the correct function for this usecase. However, zip() makes a zip type object which is an iterator. Therefore, using list() is necessary to convert the zip object into a list of tuples that can be displayed or accessed directly. The other options have logical errors.

Q179. Quand is the if __name__ == "__main__": block executed in a Python script?

The if __name__ == "__main__": block is executed when the script is run directly but not when it’s imported as a module in another script. reference

Q180. Que va be the output of the following Python code?

def square(x):
    return x * x

numbers = [1, 2, 3, 4, 5]
squared_numbers = map(square, numbers)
result = list(squared_numbers)
print(result)

The code defines a square function to calculate the square of a number. It then uses the map function to apply this function to each element in the numbers list, resulting in a new iterable. Finally, the list constructor is used to convert this iterable into a list. The output will be a list of squared numbers. reference

Q181. Quel(le) of the following is not a valid built-in function in Python?

Source

Q182. Quel(le) of the following is not a valid Python data type?

Q183. In Python, which function is used to read a line from the console input?

Reference

Q184. Que va be the output of the following Python code?

print("Hello {name1} and {name2}".format(name1='foo', name2='bin'))

Q185. What will be the ouput of the following code snippet?

def outer_func(x):
    y = x + 1
    def inner_func():
        return y + x
    return inner_func

x = 10
y = 20
closure_func = outer_func(x)
print(closure_func())

Explanation: When outer_func(10) is called, y is set to 11 within outer_func. The inner_func, which has access to outer_func’s scope, returns y + x. When closure_func() is called, it uses y = 11 (from outer_func) and x = 10 from the global scope, not from the function’s argument. Therefore, closure_func() returns 11 + 10 = 21.

Q186. What is the output of the following Python code?

x = 5
def func():
    x = 10
    print(x)
func()
print(x)

Explanation: The correct answer is 10, 5.

In the given code, the variable x is first defined in the global scope with a value of 5. Inside the func() function, a new local variable x is created and assigned the value of 10. When func() is called, it prints the value of the local x, which is 10.

After the function call, the print statement outside the function refers to the global x, which still has the value of 5.

Therefore, the output is 10, 5.

Q187. What is the output of the following Python code?

def func(a, b=2, c=3):
    print(a, b, c)

func(10)
func(10, 20)
func(10, 20, 30)

Explanation: The correct answer is 10 2 3, 10 20 3, 10 20 30.

In the given code, the func() function has three parameters: a, b, and c. b and c have default values of 2 and 3, respectively.

When func(10) is called, only the first parameter a is provided, so b and c take their default values of 2 and 3, respectively.

When func(10, 20) is called, the first parameter a is 10, and the second parameter b is 20. The third parameter c takes its default value of 3.

When func(10, 20, 30) is called, all three parameters are provided, so a is 10, b is 20, and c is 30.

Therefore, the output is: 10 2 3 10 20 3 10 20 30

Q188. What is the output of the following Python code?

x = [1, 2, 3]
y = x
y.append(4)
print(x)

Explanation: The correct answer is [1, 2, 3, 4].

In Python, assigning y = x does not create a new list; both x and y refer to the same object in memory. So when we call y.append(4), it modifies the original list that both variables point to. Thus, printing x will display the updated list [1, 2, 3, 4].

Q189. What is the output of the following Python code?

def add_item(item, item_list=[]):
    item_list.append(item)
    return item_list

print(add_item(1))
print(add_item(2))
print(add_item(3, []))

Explanation: The correct answer is [1] [1, 2] [3].

In Python, default mutable arguments (like lists) are evaluated only once when the function is defined — not each time it’s called. That means the first two calls to add_item() share the same default list, so it accumulates values [1] and then [1, 2].

However, in the third call add_item(3, []), we pass a new empty list, so it creates a separate list [3].

Q190. Quel(le) method is used to implement the len() function for a custom class?

Reference Special Methods

Q191. Que va this code output?

def decorator(func):
    def wrapper(*args, **kwargs):
        print("Before function call")
        result = func(*args, **kwargs)
        print("After function call")
        return result
    return wrapper

@decorator
def greet(name):
    print(f"Hello, {name}!")

greet("Alice")

Reference Decorators

Q192. Quel(le) statement about Python generators is correct?

Reference Generators

Q193. Qu’est-ce que the output of this code?

class Parent:
    def method(self):
        print("Parent method")

class Child(Parent):
    def method(self):
        super().method()
        print("Child method")

obj = Child()
obj.method()

Reference super()

Q194. Quel(le) method is used to implement string representation for debugging?

Reference String Representation

Q195. Que va this code output?

from functools import lru_cache

@lru_cache(maxsize=None)
def fibonacci(n):
    if n < 2:
        return n
    return fibonacci(n-1) + fibonacci(n-2)

print(fibonacci(10))
print(fibonacci.cache_info())

Reference lru_cache

Q196. Quel(le) statement about Python’s with statement is correct?

Reference with statement

Q197. Qu’est-ce que the output of this code?

class Counter:
    def __init__(self):
        self.count = 0

    def __call__(self):
        self.count += 1
        return self.count

counter = Counter()
print(counter())
print(counter())
print(counter.count)

Reference Callable Objects

Q198. Quel(le) method is used to implement the in operator for a custom class?

Reference Membership Test

Q199. Que va this code output?

from dataclasses import dataclass

@dataclass
class Point:
    x: int
    y: int

    def distance_from_origin(self):
        return (self.x ** 2 + self.y ** 2) ** 0.5

p = Point(3, 4)
print(p)
print(p.distance_from_origin())

Reference Dataclasses

Q200. Quel(le) statement about Python’s Global Interpreter Lock (GIL) is correct?

Reference GIL

Q201. Qu’est-ce que the output of this code?

class Singleton:
    _instance = None

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance

a = Singleton()
b = Singleton()
print(a is b)
print(id(a) == id(b))

Reference Singleton Pattern

Q202. Quel(le) method is used to implement iteration protocol?

Reference Iterator Protocol

Q203. Que va this code output?

from enum import Enum

class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3

print(Color.RED)
print(Color.RED.name)
print(Color.RED.value)

Reference Enum

Q204. Quel(le) statement about Python’s *args and **kwargs is correct?

Reference Variable Arguments

Q205. Qu’est-ce que the output of this code?

class MyClass:
    class_var = 0

    def __init__(self):
        MyClass.class_var += 1
        self.instance_var = MyClass.class_var

a = MyClass()
b = MyClass()
print(a.instance_var, b.instance_var)
print(MyClass.class_var)

Reference Class vs Instance Variables

Q206. Quel(le) method is used to implement the + operator for a custom class?

Reference Arithmetic Operations

Q207. Que va this code output?

from collections import namedtuple

Person = namedtuple('Person', ['name', 'age', 'city'])
p = Person('Alice', 30, 'New York')
print(p.name)
print(p[1])
print(p._fields)

Reference namedtuple

Q208. Quel(le) statement about Python’s lambda functions is correct?

Reference Lambda Expressions

Q209. Qu’est-ce que the output of this code?

from functools import partial

def multiply(x, y, z):
    return x * y * z

double = partial(multiply, 2)
result = double(3, 4)
print(result)

Reference functools.partial

Q210. Quel(le) method is used to implement comparison operations like <, >, <=, >=?

Reference Rich Comparison Methods

Q211. Que va this code output?

class MyContext:
    def __enter__(self):
        print("Entering context")
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        print("Exiting context")
        return False

with MyContext() as ctx:
    print("Inside context")

Reference Context Manager Protocol

Q212. Quel(le) statement about Python’s yield from is correct?

Reference yield from

Q213. Qu’est-ce que the output of this code?

class Descriptor:
    def __get__(self, obj, objtype=None):
        return "Descriptor value"

    def __set__(self, obj, value):
        print(f"Setting value: {value}")

class MyClass:
    attr = Descriptor()

obj = MyClass()
print(obj.attr)
obj.attr = "new value"
print(obj.attr)

Reference Descriptors

Q214. Quel(le) method is used to implement the hash() function for a custom class?

Reference Hash Method

Q215. Que va this code output?

from typing import List, Dict

def process_data(items: List[int]) -> Dict[str, int]:
    return {"count": len(items), "sum": sum(items)}

result = process_data([1, 2, 3, 4, 5])
print(result)
print(type(result))

Reference Type Hints

Q216. Quel(le) statement about Python’s __slots__ is correct?

Reference slots

Q217. Qu’est-ce que the output of this code?

class MRO_A:
    def method(self):
        print("A")

class MRO_B(MRO_A):
    def method(self):
        print("B")
        super().method()

class MRO_C(MRO_A):
    def method(self):
        print("C")
        super().method()

class MRO_D(MRO_B, MRO_C):
    def method(self):
        print("D")
        super().method()

obj = MRO_D()
obj.method()

Reference Method Resolution Order

Q218. Quel(le) method is used to implement the del statement for a custom class?

Reference Object Finalization

Q219. Que va this code output?

from contextlib import contextmanager

@contextmanager
def my_context():
    print("Setup")
    try:
        yield "resource"
    finally:
        print("Cleanup")

with my_context() as resource:
    print(f"Using {resource}")

Reference contextlib.contextmanager

Q220. Quel(le) statement about Python’s property decorator is correct?

Reference Property Decorator

Q221. Qu’est-ce que the output of the following code?

class Meta(type):
    def __new__(cls, name, bases, attrs):
        attrs['class_id'] = f"{name}_123"
        return super().__new__(cls, name, bases, attrs)

class MyClass(metaclass=Meta):
    pass

print(MyClass.class_id)

Reference Metaclasses

Q222. Quel(le) method is used to create a context manager in Python?

Reference Context Managers

Q223. Que va this code output?

import asyncio

async def fetch_data(delay):
    await asyncio.sleep(delay)
    return f"Data after {delay} seconds"

async def main():
    result = await fetch_data(1)
    print(result)

asyncio.run(main())

Reference Asyncio

Q224. Quel(le) decorator is used to create a property that can be set?

class Circle:
    def __init__(self, radius):
        self._radius = radius

    @property
    def radius(self):
        return self._radius

    @radius.setter
    def radius(self, value):
        if value < 0:
            raise ValueError("Radius cannot be negative")
        self._radius = value

Reference Property Decorators

Q225. Qu’est-ce que the output of this code?

from collections import defaultdict

dd = defaultdict(list)
dd['key1'].append('value1')
dd['key2'].append('value2')
print(len(dd))
print(dd['key3'])
print(len(dd))

Reference defaultdict