动态更改__slots__

lok*_*oki 3 python dictionary class

我正在研究一个需要__dict__通过__init__注入赋予它属性的类,如下所示:

class Torrent(Model):
    def __init__(self, d):
        super(Torrent, self).__init__('torrents')
        self.__dict__ = d
Run Code Online (Sandbox Code Playgroud)

并且需要确保不要更改对象的结构,因为实例最终会在NOSQL数据库中结束.我认为这__slots__可能会有所帮助,但我需要动态定义它.

有没有一种方法可以在没有元类的情况下实现它?

Tho*_*zco 7

使用工厂功能:

def GetTorrentClass(slots_iterable):
    class Torrent(object):
        __slots__ = slots_iterable
    return Torrent
Run Code Online (Sandbox Code Playgroud)

请注意,为了使用插槽:

  • slots_iterable 必须是可迭代的字符串
  • 你的班级必须是新式的
  • 你的类不能继承一个实现的类__dict__(即__slots__不仅仅是)

现在,你说你需要确保不要改变对象的结构',使用__slots__并不是你的问题的唯一(也可能不是最好的)解决方案:使用slot会使你的类更难在代码中使用.

相反,您可以执行以下操作:

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))
Run Code Online (Sandbox Code Playgroud)

这样,您就可以确保只将实际字段保存到数据库中.