Advertisement
Guest User

Untitled

a guest
Dec 8th, 2019
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.83 KB | None | 0 0
  1. '''
  2. Decorator що рахує кількість екземплярів
  3.  
  4.  
  5. def decor_cl(cl):
  6. count = 0
  7. class Wrapper:
  8. def __init__(self, *args):
  9. print(args)
  10. nonlocal count
  11. count += 1
  12. print("%%", count) #print in file
  13. self.wrapper = cl(*args)
  14. def __getattr__(self, item):
  15. return getattr(self.wrapper, item)
  16. return Wrapper
  17.  
  18. # def __get__(self, instance, owner):
  19. # return instance
  20.  
  21. def main_func(classobj):
  22. return decor_cl(classobj)
  23.  
  24. C = main_func(C)
  25.  
  26. '''
  27.  
  28. ##############################################
  29.  
  30. '''
  31. Змінює формат доступу до атрибуту
  32.  
  33. class A:
  34. attr1 = None
  35. def __init__(self):
  36. self.attr1 = 6
  37. pass
  38.  
  39. def attrsetter(self, value):
  40. self.attr1 = value
  41.  
  42. def attrgetter(self, name):
  43. return self.attr1
  44.  
  45.  
  46. def func(cl, attrname):
  47. setattr(cl, attrname, property(fset=attrsetter, fget=attrgetter))
  48.  
  49. func(A, 'attr')
  50. '''
  51.  
  52. ################################
  53.  
  54. '''
  55. Знайти усі дискриптори класу
  56.  
  57. def isdescriptor(cls):
  58. names = ["__get__", "__set__", "__delete__"]
  59. for name, obj in inspect.getmembers(cls):
  60. if name in names:
  61. return True
  62. return False
  63.  
  64. def get_descriptors():
  65. descriptors = list()
  66. for name, obj in inspect.getmembers(sys.modules[__name__]):
  67. if inspect.isclass(obj) and isdescriptor(obj):
  68. descriptors.append(obj)
  69. return descriptors
  70.  
  71. descriptors = get_descriptors()
  72.  
  73. def foo(cls):
  74. for name in cls.__dict__:
  75. for descr in descriptors:
  76. if isinstance(cls.__dict__[name], descr):
  77. print("descr", name)
  78.  
  79. foo(A)
  80. '''
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement