繁体   English   中英

是否可以使用装饰器修改类

[英]Is it possible to modify a class with a decorator

我正在python中编写一个类,用于某些设置,如下所示:

class _CanvasSettings:
    def __init__(self, **kwargs):
        super().__init__()
        self._size_x = _int(kwargs, 'size_x', 320)
        self._size_y = _int(kwargs, 'size_y', 240)
        self._lock_ratio = _bool(kwargs'lock_ratio', True)

    def get_size_x_var(self):
        return self._size_x
    def _get_size_x(self):
        return self._size_x.get()
    def _set_size_x(self, value):
        self._size_x.set(value)
    size_x = property(_get_size_x, _set_size_x)

    def get_size_y_var(self):
        return self._size_y
    def _get_size_y(self):
        return self._size_y.get()
    def _set_size_y(self, value):
        self._size_y.set(value)
    size_y = property(_get_size_y, _set_size_y)

    def get_lock_ratio_var(self):
        return self._lock_ratio
    def _get_lock_ratio(self):
        return self._lock_ratio.get()
    def _set_lock_ratio(self, value):
        self._lock_ratio.set(value)
    lock_ratio = property(_get_lock_ratio, _set_lock_ratio)

如你所见,我添加了块:

    def get_something_var(self):
        return self._something
    def _get_something(self):
        return self._something.get()
    def _set_something(self, value):
        self._something.set(value)
    something = property(_get_something, _set_something)

对于每一个设置。
是否可以使用decorator自动执行此任务?

我想这样做(伪代码):

def my_settings_class(cls):
    result = cls
    for field in cls:
        result.add_getter_setter_and_property( field )
    return result

@my_settings_class
class _CanvasSettings:
    def __init__(self, **kwargs):
        super().__init__()
        self._size_x = _int(kwargs, 'size_x', 320)
        self._size_y = _int(kwargs, 'size_y', 240)
        self._lock_ratio = _bool(kwargs'lock_ratio', True)

# Done !

这可能吗?
如果有,怎么样?
如何实现add_getter_setter_and_property()方法?


编辑:
这里有一个非常类似的问题: Python类装饰器
从那里的答案我怀疑有可能像我要求的那样实现,但你能告诉我如何实现add_getter_setter_and_property()函数/方法吗?


注意:
如果字符串(fe'size_x')存在,则_int()_bool()函数仅从kwargs返回_bool() Int / Bool-var eighter或者从默认值(fe 320)返回。


我的最终解决方案:我认为我找到了一个非常好的解决方案。 我只需要添加一次设置名称,这非常棒:-)

import tkinter as tk

def _add_var_getter_property(cls, attr):
    """ this function is used in the settings_class decorator to add a
    getter for the tk-stringvar and a read/write property to the class.
    cls:  is the class where the attributes are added.
    attr: is the name of the property and for the get_XYZ_var() method.
    """
    field = '_' + attr
    setattr(cls, 'get_{}_var'.format(attr), lambda self: getattr(self, field))
    setattr(cls, attr,
            property(lambda self: getattr(self, field).get(),
                     lambda self, value: getattr(self, field).set(value)))

def settings_class(cls):
    """ this is the decorator function for SettingsBase subclasses.
    it adds getters for the tk-stringvars and properties. it reads the
    names described in the class-variable _SETTINGS.
    """
    for name in cls._SETTINGS:
        _add_var_getter_property(cls, name)
    return cls


class SettingsBase:
    """ this is the base class for a settings class. it automatically
    adds fields to the class described in the class variable _SETTINGS.
    when you subclass SettingsBase you should overwrite _SETTINGS.
    a minimal example could look like this:

      @settings_class
      class MySettings(SettingsBase):
          _SETTINGS = {
              'x': 42,
              'y': 23}

    this would result in a class with a _x tk-intvar and a _y tk-doublevar
    field with the getters get_x_var() and get_y_var() and the properties
    x and y.
    """

    _SETTINGS = {}

    def __init__(self, **kwargs):
        """ creates the fields described in _SETTINGS and initialize
        eighter from the kwargs or from the default values
        """
        super().__init__()
        fields = self._SETTINGS.copy()
        if kwargs:
            for key in kwargs:
                if key in fields:
                    typ = type(fields[key])
                    fields[key] = typ(kwargs[key])
                else:
                    raise KeyError(key)
        for key in fields:
            value = fields[key]
            typ = type(value)
            name = '_' + key
            if typ is int:
                var = tk.IntVar()
            elif typ is str:
                var = tk.StringVar()
            elif typ is bool:
                var = tk.BooleanVar()
            elif typ is float:
                var = tk.DoubleVar()
            else:
                raise TypeError(typ)
            var.set(value)
            setattr(self, name, var)

之后我的设置类看起来像这样:

@settings_class
class _CanvasSettings(SettingsBase):

    _SETTINGS = {
        'size_x': 320,
        'size_y': 240,
        'lock_ratio': True
        }

这个类的装饰员。

def add_get_set(cls):
    for prop in cls.PROPERTIES:
        # Note cannot be "lambda self: getattr(self, prop)" because of scope prop changes to be the last item in PROPERTIES
        setattr(cls, "get"+prop, lambda self, attr=prop: getattr(self, attr))

    return cls

@add_get_set
class _CanvasSettings:
    PROPERTIES = ["_size_x", "_size_y", "_lock_ratio"]

    def __init__(self, **kwargs):
        super().__init__()

        for prop in self.PROPERTIES:
            setattr(self, prop, 0)

c = _CanvasSettings()
print(c.get_size_y())

您可以将函数设置为变量

class _CanvasSettings:
    def __init__(self, **kwargs):
        super().__init__()
        self._size_x = _int(kwargs, 'size_x', 320)
        self._size_y = _int(kwargs, 'size_y', 240)
        self._lock_ratio = _bool(kwargs'lock_ratio', True)

        for variable in ["_size_x", "_size_y", "_lock_ratio"]:
            setattr(self, "get"+variable, lambda: getattr(self, variable))
            # bind the method (Not sure if binding the method gets you anything)
            #setattr(self, "get"+variable, (lambda self: getattr(self, variable)).__get__(self, self.__class__))

备用

class _CanvasSettings:
    def __init__(self, **kwargs):
        super().__init__()
        self._size_x = _int(kwargs, 'size_x', 320)
        self._size_y = _int(kwargs, 'size_y', 240)
        self._lock_ratio = _bool(kwargs'lock_ratio', True)

        for variable in dir(self):
            if variable.startswith("_") and not variable.startswith("__"):
                self.__dict__["get"+variable] = lambda: getattr(self, variable)

使用setattr将函数和属性绑定为类对象的属性当然可以做你想要的事情:

def add_getter_setter_property(cls, attrib_name):
    escaped_name = "_" + attrib_name
    setattr(cls, "get_{}_var".format(attrib_name),
            lambda self: getattr(self, escaped_name))
    setattr(cls, attrib_name,
            property(lambda self: getattr(self, escaped_name).get()
                     lambda self, value: getattr(self, escaped_name).set(value)))

在这里,我正在跳过为property使用的gettersetter方法命名。 如果你真的想要,可以将它们添加到课堂中,但我认为这可能是不必要的。

棘手的一点可能实际上是找到你需要应用它的属性名称。 与您的示例不同,您不能迭代类对象以获取其属性。

最简单的解决方案(从实现的角度来看)是要求类在类变量中指定名称:

def my_settings_class(cls):
    for field in cls._settings_vars:
        add_getter_setter_and_property(cls, field)
    return cls

@my_settings_class
class _CanvasSettings:
    _settings_vars = ["size_x", "size_y", "lock_ratio"]
    def __init__(self, **kwargs):
        super().__init__()
        self._size_x = _int(kwargs, 'size_x', 320)
        self._size_y = _int(kwargs, 'size_y', 240)
        self._lock_ratio = _bool(kwargs, 'lock_ratio', True)

更加用户友好的方法可能使用dirvars来检查类变量并挑选出需要自动vars行的变量。 您可以使用isinstance检查值是否具有特定类型,或者在属性名称中查找特定模式。 我不知道什么是最适合您的具体用途,所以我会留给您。

作为自动化制作属性的替代方法,您可以重载__getattr____setattr__以检测私有字段何时可用适当的getter或setter方法:

class Field: # so I could test it.
    def __init__(self,args,name,default):
        self.name = name
        self.value = default
    def get(self):
        return self.value
    def set(self,value):
        self.value = value

class CanvasSettings:
    def __init__(self, **kwargs):
        super().__init__()
        self._size_x = Field(kwargs, 'size_x', 320)
        self._size_y = Field(kwargs, 'size_y', 240)
        self._lock_ratio = Field(kwargs, 'lock_ratio', True)

    def __getattr__(self, attr):
        private_name = "_" + attr
        field = object.__getattribute__(self, private_name) #this will fail for non-special attributes
        getter = getattr(field,"get",None)
        if getter is None:
            raise AttributeError("Private member did not have getter") #may want to change the error handling
        else:
            return getter()

    def __setattr__(self,attr, value):
        private_name = "_" + attr
        try:
            field = getattr(self,private_name)
        except AttributeError:
            # if there is no private field or there is but no setter
            # resort back to defaualt behaviour.
            return super().__setattr__(attr,value)
        else:
            setter = getattr(field, "set", None)
            if setter is None:
                raise AttributeError("private field does not have a setter")
            setter(value)

然后当你尝试获取或设置thing.size_x ,它将首先查找thing._size_x并检查一个合适的方法,这是一个演示:

>>> thing = CanvasSettings()
>>> thing._size_x.value
320
>>> thing.size_x
320
>>> thing.size_x = 5
>>> 5 == thing.size_x == thing._size_x.value
True

每次检索属性时检查现有字段可能会对性能造成损害,但如果您有许多具有适合此模型的私有字段的类,我只想提供此选项。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM