Advertisement
mbazs

Python ABC / Virtual Subclasses

Nov 9th, 2020
1,315
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.08 KB | None | 0 0
  1. from abc import ABC, abstractmethod
  2.  
  3.  
  4. class A(ABC):
  5.     def __init__(self):
  6.         self.a = 0
  7.         pass
  8.  
  9.     @abstractmethod
  10.     def hello(self):
  11.         pass
  12.  
  13.     @classmethod
  14.     def __subclasshook__(cls, K):
  15.         if K is tuple:
  16.             return True
  17.         return NotImplemented
  18.  
  19.  
  20. class B(A):
  21.     def __init__(self):
  22.         super().__init__()
  23.  
  24.     def hello(self):
  25.         print('B hello')
  26.  
  27.  
  28. class C(B):
  29.     def __init__(self):
  30.         super().__init__()
  31.  
  32.     def hello(self):
  33.         print('C hello')
  34.  
  35.     def chk(self):
  36.         for c in C.__mro__:
  37.             print(c)
  38.  
  39.     def __getitem__(self, item):
  40.         if item >= 3:
  41.             raise IndexError('index out of range: {}'.format(item))
  42.         return item
  43.  
  44.     def __len__(self):
  45.         return 3
  46.  
  47.  
  48. def main():
  49.     t = 1, 2, 3
  50.     c = C()
  51.     c.hello()
  52.     c.chk()
  53.  
  54.     # these are ok
  55.     print(isinstance(c, A))
  56.     print(isinstance(c, B))
  57.     print(isinstance(c, C))
  58.  
  59.     # what's the use??
  60.     print(issubclass(tuple, A))
  61.  
  62.  
  63. if __name__ == '__main__':
  64.     main()
  65.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement