Advertisement
fkudinov

Усі секрети Классметоду / Python classmethod internals

Jan 27th, 2024
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.78 KB | Source Code | 0 0
  1. class MyBoundClassMethod:
  2.  
  3.     def __init__(self, func, cls):
  4.         self.func = func
  5.         self.cls = cls
  6.  
  7.     def __call__(self, *args, **kwargs):
  8.         return self.func(self.cls, *args, **kwargs)
  9.  
  10.  
  11. class MyClassMethod:
  12.  
  13.     def __init__(self, func):
  14.         self.func = func
  15.  
  16.     def __get__(self, instance, owner):
  17.         return MyBoundClassMethod(self.func, owner)
  18.  
  19.  
  20. class MyClass:
  21.  
  22.     @classmethod
  23.     def print_message(cls, msg):
  24.         print(f"id {id(cls)}, self {cls}, '{msg}'")
  25.  
  26.     @MyClassMethod
  27.     def print_message_2(cls, msg):
  28.         print(f"id {id(cls)}, self {cls}, '{msg}'")
  29.  
  30.  
  31. MyClass.print_message("Hi there")
  32. MyClass.print_message_2("Hi there")
  33.  
  34. my_obj = MyClass()
  35. my_obj.print_message("Hi there")
  36. my_obj.print_message_2("Hi there")
  37.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement