Last active
August 23, 2021 11:06
-
-
Save IgorZyktin/4ceaa8bc10e227eaaaafd87b95e59446 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# простейший дженерик ---------------------------------------- | |
from typing import Generic | |
from typing import TypeVar | |
T = TypeVar('T') | |
class Cool(Generic[T]): | |
def __init__(self): | |
self._storage = [] | |
def put(self, something: T) -> None: | |
self._storage.append(something) | |
def pop(self) -> T: | |
return self._storage.pop() | |
array: Cool[int] = Cool() | |
array.put(1) # Ok | |
array.put('wtf') # Expected type 'int' (matched generic type 'T'), got 'str' instead | |
# простейший абстрактный базовый класс --------------------- | |
from abc import ABC | |
from abc import abstractmethod | |
class Parent(ABC): | |
@abstractmethod | |
def must_implement(self): | |
"""Abstract.""" | |
class Child(Parent): | |
pass | |
c = Child() # TypeError: Can't instantiate abstract class Child with abstract method must_implement | |
# простейший протокол --------------------- | |
from typing import Protocol | |
class DoProtocol(Protocol): | |
def do(self) -> int: | |
pass | |
class SomethingInt: | |
def do(self) -> int: | |
return 1 | |
class SomethingStr: | |
def do(self) -> str: | |
return 'sd' | |
def some_func(something: DoProtocol) -> None: | |
print(something) | |
some_func(SomethingInt()) # Ok | |
some_func(SomethingStr()) # Expected type 'DoProtocol', got 'SomethingStr' instead |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment