[英]change __slots__ dynamically
我正在研究一个需要通过__init__
注入为其赋予__dict__
属性的类,如下所示:
class Torrent(Model):
def __init__(self, d):
super(Torrent, self).__init__('torrents')
self.__dict__ = d
并且需要确保不更改对象的结构,因为该实例将最终存储在NOSQL数据库中。 我认为__slots__
可能会有所帮助,但我需要动态定义它。
没有元类,有没有办法使之成为可能?
使用工厂功能:
def GetTorrentClass(slots_iterable):
class Torrent(object):
__slots__ = slots_iterable
return Torrent
请注意,为了使用插槽:
slots_iterable
必须是字符串的可迭代 __dict__
的类(即,不仅限于__slots__
) 现在,您说您“需要确保不更改对象的结构”,使用__slots__
并不是解决问题的唯一方法(也许也不是最好的):使用插槽会使类更难在代码中使用。
相反,您可以执行以下操作:
class Torrent(object):
def __init__(self, fields):
self.fields = fields #Fields could be ('field1', 'field2')
def save(self):
for field in self.fields:
self.store_to_db(field, getattr(self, field))
这样,您可以确保仅将实际字段保存到数据库中。
这应该可以满足您的需求。
def construct_slots(slots):
class SlotClass(object):
__slots__ = slots
def __init__(self, *args, **kwargs):
for slot, arg in zip(SlotClass.__slots__, args):
setattr(self, slot, arg)
for key, value in kwargs:
setattr(self, key, value)
return SlotClass
Torrent = construct_slots(("a",'b','c'))
a = Torrent(1,2,3)
print a.a
print a.b
__slots__
和__dict__
通常是替代方法。 无论哪种情况,元类都不会帮助您为实例动态创建它们,除了自定义元类可以放宽对__dict__
赋值的限制(Django已经做到了)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.