Advertisement
Guest User

Untitled

a guest
Nov 26th, 2014
151
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.68 KB | None | 0 0
  1. #!/usr/bin/env python3
  2.  
  3. __author__ = "Andrew Kozlov"
  4. __copyright__ = "Copyright 2014, SPbAU"
  5.  
  6.  
  7. class WithFinals(type):
  8.     __methods = {}
  9.     __final_methods = {}
  10.     __decorated_methods = []
  11.  
  12.     def __init__(cls, *args, **kwargs):
  13.         methods = dict(args[2])
  14.         WithFinals.__methods[cls] = methods
  15.  
  16.         WithFinals.__final_methods[cls] = {}
  17.         for method in WithFinals.__decorated_methods:
  18.             if method == methods.get(method.__name__):
  19.                 WithFinals.__final_methods[cls][method.__name__] = method
  20.  
  21.         resolved = {}
  22.         for base in cls.mro():
  23.             methods = WithFinals.__methods[base] if base in WithFinals.__methods else base.__dict__.copy()
  24.  
  25.             if base in WithFinals.__final_methods:
  26.                 for name in methods:
  27.                     if name in resolved and name in WithFinals.__final_methods[base]:
  28.                         raise TypeError(
  29.                             'Method \'' + name + '\' of class \'' + base.__name__ + '\' can not be overridden')
  30.  
  31.             resolved.update(methods)
  32.  
  33.     @staticmethod
  34.     def final(method):
  35.         WithFinals.__decorated_methods.append(method)
  36.  
  37.         return method
  38.  
  39.  
  40. def final(method):
  41.     return WithFinals.final(method)
  42.  
  43.  
  44. class Foo():
  45.     def foo(self):
  46.         print('foo')
  47.  
  48.  
  49. class Bar(Foo):
  50.     pass
  51.  
  52.  
  53. class Baz(Bar, metaclass=WithFinals):
  54.     @final
  55.     def foo(self):
  56.         print('baz')
  57.  
  58.  
  59. class BarBaz(Baz, Bar):
  60.     def foo(self):
  61.         print('bar baz')
  62.  
  63. # class Bar(metaclass=WithFinals):
  64. #     @final
  65. #     def foo(self):
  66. #         print('bar')
  67. #
  68. #
  69. # class Baz(Foo, Bar):
  70. #     pass
  71.  
  72. if __name__ == '__main__':
  73.     pass
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement