Python


https://www.interviewbit.com/python-interview-questions/


Sta je razlika izmedju tuple i list?


List comprehension

Novi sintaksicki nacin kako da se difinise nova lista: [ expresion for item in interable if condition ]

Npr: [ x**2 for x in range(5) if x % 2 == 0 ]


Sta je dict in python, how to use it?

Rečnik (dict) u python je unordered kolekcija podataka kljuc:vrednost. Kljuc mora da bude jednistven.

osobine = { "name" : "Petar", "surname" : "Petrovic", "age" : 26 }

osobine["age"] = 30;
print(osobine["name"])
del osobine["surname"]
print("name" in osobine) # check if key exists

deepcody vs shallow copy


Kako se odrzava memorija u pythonu?

Garbage collection, reference counting (each object has a count of how many references point to it, when it drops to zero, object is deallocated)

Memory Pooling: Python uses an internal memory allocator (e.g., pymalloc) to efficiently manage small objects, reducing overhead of frequent memory allocation.


Singleton sablon u pthonu

Osigurava da postoji samo jedna istanca klase tokom izvrsavanja:

class Singleton:
    _instance = None

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

obj1 = Singleton()
obj2 = Singleton()

print(obj1 is obj2)

Decorators in python

Decorators in Python are functions that modify the behavior of other functions or methods. They allow you to wrap additional functionality around an existing function without changing its core structure.

A decorator is a function that takes another function as input and returns a new function that enhances the original function’s behavior.

def decorator(func):
    def wrapper():
        print("Before the function")
        func()
        print("After the function")
    return wrapper

@decorator
def say_hello():
    print("Hello!")

# @decorator is short for this:
# say_hello = decorator(say_hello)

say_hello()

@staticmethod vs @classmethod

@staticmethod does not know about the class or instance, while @classmethod has access to the class and can modify class state.

class MyClass:
    @staticmethod
    def static_method():
        print("Static method")

MyClass.static_method()  # Can be called on the class

class MyClass:
    @classmethod
    def class_method(cls):
        print("Class method")

MyClass.class_method()  # Can be called on the class