python 10 problems

read

Question 1

what’s your differences between “__new__”, “__init__” and “__call__”? what’s your differences between “cls” and “self”?

Answer 1:

__new__: creates the instance of a Class, you use it when you need to control the creation of a new instance.
__new__ accepts “cls” as it’s first parameter but __init__ accepts “self”. __new__ can return value especially class

__init__: used to initialize the instance variables once the instance is created by __new__. no return value

__call__: like a function call operator. Once you implement __call__ in your Class, you can invoke the Class instance as a function call.

self: instance self, you can’t call class staticmethod
cls: class self, you can call class staticmethod

Question2

Singleton Pattern Design with at least 4 methods

Answer2:

  1. class with a get_client method
  2. class with __new__ method
  3. global instance from your defined class

Question3

Try to design a decorator to disturb/delay async task for avoiding triggering frequency control

Answer3:

# coding: utf-8

import time
import random
import functools


def shuffle_time_gap(func):

    FUNC_DICT = dict()

    @functools.wraps(func)
    def _func(*args, **kws):
        now = int(time.time())
        if FUNC_DICT.get(func.__name__, 0) >= now - 1:
            time_random_gap = random.randint(11, 12) / 1000
            time.sleep(time_random_gap)

        FUNC_DICT[func.__name__] = now
        return func(*args, **kws)

    return _func