Как с помощью метакласса создать сеттер класса в Python?
Я хочу сделать метакласс, который переделывает методы класса в property и setter. Например, у меня есть такой класс:
class TestClass():
def __init__(self, x: int):
self._x = x
def get_x(self):
print("this is property")
return self._x
def set_x(self, x: int):
print("this is setter")
self._x = x
А я хочу, чтобы он работал так:
class TestClass():
def __init__(self, x: int):
self._x = x
@property
def x(self):
print("this is property")
return self._x
@x.setter
def x(self, x: int):
print("this is setter")
self._x = x
Пока что я смогла понять, как это можно сделать для property:
class PropertyConvert(type):
def __new__(cls, future_class_name, future_class_parents, future_class_attr):
new_attr = {}
for name, val in future_class_attr.items():
if not name.startswith('__'):
if name.startswith('get_'):
new_attr[name[4:]] = property(val)
if name.startswith('set_'):
# ???
else:
new_attr[name] = val
return type.__new__(cls, future_class_name, future_class_parents, new_attr)
Но не могу понять, что делать с сеттером.
Ответы (1 шт):
Автор решения: Piboldi Refliction
→ Ссылка
Функция setter-а передается в функцию property() вторым параметром.