Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (19.9k points)

I'm working with generics in python, and want to know if I can achieve generics in python as other languages. The syntax needs not to be same as other languages but if I can do something like

template<typename T>

class List {

public:

    T array[10];

};

int main() {

    List<int> list;

}

I tried the below code but I'm not sure how can I achieve the same as C++ or Java. Like, I shouldn't be allowed to add objects of any other type once I define the data type on initialization.

from typing import TypeVar, Generic, List

T = TypeVar('T')

class CircularQueue(Generic[T]):

    def __init__(self):

        self._front = 0

        self._rear = 0

        self._array = list()

    def mod(self, x): return (x+1) % (len(self._array)+1)

    @property

    def is_full(self):

        return self.mod(self._rear) == self.mod(self._front) + 1

    def insert(self, element: T):

        if not self.is_full:

            self._rear += 1

            self._array.append(element)

if __name__ == "__main__":

    # I want to Initialize the queue as cQueue = CircularQueue<int>()

    # Something that other compiled languauges offer

    # Is it possible to do so?

    # Or any other method so that I can restrict the type of objects.

    cQueue = CircularQueue()

    cQueue.insert(10)

    # Here I want to raise an error if I insert any other type of Object

    cQueue.insert('A')  

1 Answer

0 votes
by (25.1k points)

Since python is not a statically typed language like Java or C++, it does not have the concept of generics.one could say that every function is generic because parameters are not actually typed.

Related questions

0 votes
1 answer
0 votes
1 answer

Browse Categories

...