凝结pyqtproperties(condense pyqtproperties)

2019-06-27 00:15发布

我用Python写一个脚本,并有一点问题:

class LightDMUser(QObject):
  def __init__(self, user):
    super(LightDMUser, self).__init__()
    self.user = user

  @pyqtProperty(QVariant)
  def background(self):      return self.user.get_background()

  @pyqtProperty(QVariant)
  def display_name(self):    return self.user.get_display_name()

  @pyqtProperty(QVariant)
  def has_messages(self):    return self.user.get_has_messages()

  @pyqtProperty(QVariant)
  def home_directory(self):  return self.user.get_home_directory()

  @pyqtProperty(QVariant)
  def image(self):           return self.user.get_image()

  @pyqtProperty(QVariant)
  def language(self):        return self.user.get_language()

  @pyqtProperty(QVariant)
  def layout(self):          return self.user.get_layout()

  @pyqtProperty(QVariant)
  def layouts(self):         return self.user.get_layouts()

  @pyqtProperty(QVariant)
  def logged_in(self):       return self.user.get_logged_in()

  @pyqtProperty(QVariant)
  def name(self):            return self.user.get_name()

  @pyqtProperty(QVariant)
  def real_name(self):       return self.user.get_real_name()

  @pyqtProperty(QVariant)
  def session(self):         return self.user.get_session()

正如你所看到的,这个代码是可怕的冗余。 我试图冷凝它是这样的:

class LightDMUser(QObject):
  attributes = ['background', 'display_name', 'has_messages', 'home_directory', 'image', 'language', 'layout', 'layouts', 'logged_in', 'name', 'real_name', 'session']

  def __init__(self, user):
    super(LightDMUser, self).__init__()
    self.user = user

    for attribute in self.attributes:
      setattr(self, attribute, pyqtProperty(QVariant, getattr(self.user, 'get_' + attribute)))

PyQt4的,但是,预计类的方法是存在的类本身,而不是一个实例。 移动setattr码出的__init__块没有工作,要么是因为self没有为类定义的,所以我真的不知道该怎么办。

任何人都可以看到的方式来凝聚这个代码?

Answer 1:

有很多方法去做号:类装饰,元类,密新。

常见的辅助函数:

def set_pyqtproperties(klass, properties, proxy='user'):
    def make_prop(prop):        
        def property_(self):
            return getattr(getattr(self, proxy), 'get_' + prop)
        property_.__name__ = prop
        return property_

    if isinstance(properties, basestring):
       properties = properties.split()
    for prop in properties:
         setattr(klass, prop, pyqtProperty(QVariant, make_prop(prop)))

装饰类

def set_properties(properties):
    def decorator(klass):
        set_pyqtproperties(klass, properties)
        return klass
    return decorator
Usage
@set_properties("display background")
class LightDMUser(QObject): pass

如果有类装饰不支持,那么你可以尝试:

class LightDMUser(QObject): 
    pass
LightDMUser = set_properties("display background")(LightDMUser)

元类

def set_properties_meta(properties):
    def meta(name, bases, attrs):
        cls = type(name, bases, attrs)
        set_pyqtproperties(cls, properties)
        return cls
    return meta
Usage
class LightDMUser(QObject):
    __metaclass__ =  set_properties_meta("display background")

注意:如果你设置属性为一类属性的列表,你可以重复使用相同的元类:

def MetaClass(name, bases, attrs):
    cls = type(name, bases, attrs)
    set_pyqtproperties(cls, attrs.get('properties', ''))
    return cls

class LightDMUser(QObject):
    properties = "display background"
    __metaclass__ = MetaClass

你也可以操纵attrs直接: attrs[name] = value之前调用type()而不是setattr(cls, name, value)

上述假定QObject.__class__ is type

Mixin

def properties_mixin(classname, properties):
    #note: create a new class by whatever means necessary
    # e.g., even using exec() as namedtuple does
    # http://hg.python.org/cpython/file/3.2/Lib/collections.py#l235

    # reuse class decorator here
    return set_properties(properties)(type(classname, (), {}))
Usage
PropertiesMixin = properties_mixin('PropertiesMixin', 'display background')
class LightDMUser(PropertiesMixin, QObject): pass

我还没有尝试过它的任何。 该代码是在这里显示的金额,它可能需要对实现该功能的一种代码。



Answer 2:

你可以附上类定义的еру外面这些方法:

class LightDMUser(QObject):

  def __init__(self, user):
    super(LightDMUser, self).__init__()
    self.user = user

最简单的方法是创建一个封闭的每个属性,覆盖其__name__ (只是情况下,如果@pyqtProperty需要它),将其绑定到类:

for attribute in [
        'background',
        'display_name',
        'has_messages',
        'home_directory',
        'image',
        'language',
        'layout',
        'layouts',
        'logged_in',
        'name',
        'real_name',
        'session'
      ]:

  def delegating(self):
    return getattr(self.user, 'get_' + attribute)()

  delegating.__name__ = attribute
  delegating = pyqtProperty(QVariant)(delegating)

  setattr(LightDMUser, attribute, delegating)


Answer 3:

我敢肯定,如果你移动你的环出的类,并创建一个封闭来保存每个属性名称的这个可以工作:

class LightDMUser(QObject):
    attributes = ['background', 'display_name', 'has_messages',
                  'home_directory', 'image', 'language', 'layout',
                  'layouts', 'logged_in', 'name', 'real_name', 'session']

    def __init__(self, user):
        super(LightDMUser, self).__init__()
        self.user = user

for attribute in LightDMUser.attributes:
    closure = lambda self, attribute=attribute : getattr(self.user,
                                                         'get_' + attribute)()
    setattr(LightDMUser, attribute, pyqtProperty(QVariant, closure))

我没有跟你处理实际的基于Qt类测试这一点,但使用常规的Python简化版本property实例完美。 我也不能肯定这是个好主意,因为这将是非常很难搞清楚发生了什么事情,如果你不熟悉它。



Answer 4:

我不相信我喜欢这个,但它是一个可能的选择,是不是太难理解,并消除了需要getattr的...以下可以使用有点像宏-但可能需要调整。 ..(如采取funcs中从类定义startwith获得,或从现有对象等)的一个也有中添加再版来形容它是一个支持类具有属性对用户对象或任何接口.. 。)

def get_properties(name, funcs):
    get_text = """
class {name}(QObject):
""".format(name=name)
    for func in funcs:
        get_text += (
              "\n\t@pyqtProperty(QVariant)\n"
              "\tdef {func}(self): return self.user.get_{func}()\n"
              ).format(func=func)

    print get_text # this should be exec...

>>> get_properties('UserProperties', ['display', 'background'])

class UserProperties(QObject):

    @pyqtProperty(QVariant)
    def display(self): return self.user.get_display()

    @pyqtProperty(QVariant)
    def background(self): return self.user.get_background()

当exec'd,你写你的主类的能力:

class LightDMUser(QObject, UserProperties):
    def __init__(self, user):
        super(LightDMUser, self).__init__()
        self.user = user


Answer 5:

我测试下面的解决方案,用于Python 3.它使用的元类关键字

# A bit of scaffolding

def pyqtProperty(cls, method):
    return method

class QObject:
    pass

class QVariant:
    pass

class User:
    def __init__(self, name="No Name"):
        self.name = name
    def get_background(self):
        return self.name
    def get_display_name(self):
        return self.name
    def get_has_messages(self):
        return self.name
    def get_home_directory(self):
        return self.name
    def get_image(self):
        return self.name
    def get_language(self):
        return self.name
    def get_layout(self):
        return self.name
    def get_layouts(self):
        return self.name
    def get_logged_in(self):
        return self.name
    def get_name(self):
        return self.name
    def get_real_name(self):
        return self.name
    def get_session(self):
        return self.name

# The Meta Class
class MetaLightDMUser(type):
    @classmethod
    def __prepare__(cls, name, baseClasses):
        classdict = {}
        for attribute in ['background', 'display_name', 'has_messages', 'home_directory', 'image', 'language', 'layout', 'layouts', 'logged_in', 'name', 'real_name', 'session']:
            classdict[attribute] = eval("lambda self: pyqtProperty(QVariant, getattr(self.user, 'get_" + attribute +"'))()")
        return classdict

    def __new__(cls, name, baseClasses, classdict):
        return type.__new__(cls, name, baseClasses, classdict)

# The class itself
class LightDMUser(QObject, metaclass = MetaLightDMUser): 
    def __init__(self, user):
        super(LightDMUser, self).__init__()
        self.user = user

我也可以创造这样的classdict项

classdict[attribute] = lambda self, attr=attribute: pyqtProperty(QVariant, getattr(self.user, 'get_' + attr))()

但提出了一个ATTR说法。 随着eval() ,我们硬核这个说法

同样,我们也可以使用functools.partial

classdict[attribute] = functools.partial(lambda self, attr: pyqtProperty(QVariant, getattr(self.user, 'get_' + attr))(), attr=attribute)

但随后的呼叫必须被u.method(u) 它不能被u.method()

呼叫LightDMUser.method(u)适用于所有3个实现

问候



Answer 6:

这是棘手的削减使用元类或类装饰样板为pyqtProperty,但是这是我们刚刚在这里工作,这将有助于为出发点。 不足之处,我想,是你不再得到使用@decorator语法,但它似乎像擀成单行这个代码是在这种情况下更可取。

您可以设置这件事,而不是通过打电话给你的用户对象只是自己的,或者你可以实施LightDMUser,将调用通过自动self.user定制GETATTR行为。

from PyQt4.QtCore import pyqtProperty
from PyQt4.QtGui import QWidget, QColor
from functools import partial

def pyqtPropertyInit(name, default):
    def _getattrDefault(default, self, attrName):
        try:
            value = getattr(self, attrName)
        except AttributeError:
            setattr(self, attrName, default)
            return default
        return value
    ga = partial(_getattrDefault, default)
    return pyqtProperty(
        default.__class__,
        fget=(lambda s: ga(s, name)),
        fset=(lambda s, v: setattr(s, name, v)),
    )

class TestClass(QWidget):
    def __init__(self, *args, **kwargs):
        super(TestClass, self).__init__(*args, **kwargs)

    stdoutColor = pyqtPropertyInit('_stdoutColor', QColor(0, 0, 255))
    pyForegroundColor = pyqtPropertyInit('_pyForegroundColor', QColor(0, 0, 255))


文章来源: condense pyqtproperties