Advertisement
Noam_15

generic_property.py

Jan 24th, 2022
1,093
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.86 KB | None | 0 0
  1. from typing import TypeVar, Generic
  2.  
  3.  T = TypeVar('T', bound=str) # T is str or subtype of str
  4.  
  5.  class Stack(Generic[T]):
  6.      def __init__(self, initial_items: list[T]=None) -> None:
  7.          if not initial_items:
  8.              initial_items = []
  9.          self.items: list[T] = initial_items
  10.  
  11.      def push(self, item: T) -> None:
  12.          self.items.append(item)
  13.  
  14.      def pop(self) -> T:
  15.          return self.items.pop()
  16.  
  17.      @property
  18.      def first(self) -> T:
  19.          return self.items[0]
  20.  
  21.  s1 = Stack[str]()
  22.  s1.push('A')
  23.  b1 = s1.items[0].endswith('Z') # bool | Any
  24.  
  25.  s2 = Stack() # default type
  26.  s2.push('B')
  27.  b2 = s2.items[0].endswith('Z') # bool | Any
  28.  
  29.  s3 = Stack[str]()
  30.  s3.push('C')
  31.  b3 = s3.first.endswith('Z') # bool
  32.  
  33.  s4 = Stack() # default type with property
  34.  s4.push('D')
  35.  b4 = s4.first.endswith('Z') # Any (Why??)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement