Advertisement
fkudinov

ООП із Словників та Функцій / Реалізація із словників та функцій

Apr 4th, 2024
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.45 KB | Source Code | 0 0
  1. def greeting(person):
  2.     print("My name {}, and I am a {}".format(
  3.         getattr(person, "get_name")(),
  4.         getattr(person, "get_employment")(),
  5.     ))
  6.  
  7.  
  8. def get_name(person):
  9.     return getattr(person, "name")
  10.  
  11.  
  12. def get_employment(person):
  13.     return getattr(person, "employment")
  14.  
  15.  
  16. def getattr(person, attr):
  17.     if attr in person:
  18.         return person[attr]
  19.  
  20.     if attr not in person["base"]:
  21.         raise AttributeError(f"attr {attr} not found")
  22.  
  23.     val = person["base"][attr]
  24.     if callable(val):
  25.  
  26.         def func(*args, **kwargs):
  27.             return val(person, *args, **kwargs)
  28.  
  29.         return func
  30.  
  31.     return val
  32.  
  33.  
  34. def create(base, *args, **kwargs):
  35.     new_item = base["new"](base)
  36.     base["init"](new_item, *args, **kwargs)
  37.     return new_item
  38.  
  39.  
  40. def new(base):
  41.     return {"base": base}
  42.  
  43.  
  44. def init(person, name, employment=None):
  45.     person["name"] = name
  46.     if employment is not None:
  47.         person["employment"] = employment
  48.  
  49.  
  50. person_base = {
  51.     "employment": "Unemployed",
  52.     "greeting": greeting,
  53.     "get_name": get_name,
  54.     "get_employment": get_employment,
  55.  
  56.     "new": new,
  57.     "init": init
  58. }
  59.  
  60. # --------------------
  61.  
  62. person_1 = create(person_base, "John", "Doctor")
  63. person_2 = create(person_base, "Mathew", "Teacher")
  64. person_3 = create(person_base, "Mathew")
  65.  
  66. # --------------------
  67.  
  68. getattr(person_1, "greeting")()
  69. getattr(person_2, "greeting")()
  70. getattr(person_3, "greeting")()
  71.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement