Advertisement
BERKYT

Implementing classes on functions

Jun 19th, 2023 (edited)
917
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.35 KB | None | 0 0
  1. def Class(*base_classes):
  2.     def add_base_class_attrs_to_inst(instance):
  3.         for cls in base_classes:
  4.             for name, attr in cls().__dict__.items():
  5.                 if instance.__dict__.get(name) is None:
  6.                     instance.__dict__[name] = attr
  7.  
  8.         return instance
  9.  
  10.     def init_class(func):
  11.         def wrapper(*args):
  12.             instance = func(lambda: ..., *args)
  13.             return add_base_class_attrs_to_inst(instance)
  14.         return wrapper
  15.     return init_class
  16.  
  17.  
  18. @Class()
  19. def BaseClass(self):
  20.     def constructor():
  21.         self.test = test
  22.         self.test2 = test2
  23.  
  24.         return self
  25.  
  26.     def test():
  27.         print('A test')
  28.  
  29.     def test2():
  30.         print('A test2')
  31.  
  32.     return constructor()
  33.  
  34.  
  35. @Class()
  36. def BaseClass2(self):
  37.     def constructor():
  38.         self.test3 = test3
  39.  
  40.         return self
  41.  
  42.     def test3():
  43.         print('A test3')
  44.  
  45.     return constructor()
  46.  
  47.  
  48. @Class(BaseClass, BaseClass2)
  49. def user(self, x):
  50.     def constructor():
  51.         self.x = x
  52.         self.print_info = print_info
  53.         self.test = test
  54.  
  55.         return self
  56.  
  57.     def print_info(self=self):
  58.         print(f'x = {self.x}')
  59.  
  60.     def test():
  61.         print('Is override')
  62.  
  63.     return constructor()
  64.  
  65.  
  66. c = user(1)
  67. c2 = user(122)
  68.  
  69. c.print_info()
  70. c2.print_info()
  71. c2.test()
  72. c2.test2()
  73. c2.test3()
  74.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement