我正在用 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
没有为类定义,所以我真的不知道该怎么做。
任何人都可以看到压缩此代码的方法吗?