python - 动态改变 __slots__

标签 python class dictionary

我正在开发一个需要通过 __init__ 注入(inject)来为其赋予 __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 必须是一个可迭代的字符串
  • 你的类(class)必须是新式的
  • 您的类不能继承实现 __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))

这样,您就可以确定只有您的实际字段会保存到您的数据库中。

关于python - 动态改变 __slots__,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10822154/

相关文章:

c++ - 在用C++初始化对象时遇到问题-Linux

python - 我正在寻找根据用户输入创建类的实例

python - virtualGraph 和 pipelineStage Graphcore 的 PopART/Poplar 库的区别

python - 不使用 grequests.map() 的延时 grequests

python - 为什么在 python 中将集合初始化为 `{*()}` 比 `set()` 快?

java - java中的继承和数组列表

python尝试除了不工作

.net - VB.NET 中 Dictionary(Of String, SomeReferenceType) 的性能

string - 如何将两个字符串转换为 perl 中的散列?

python - "OrderedDict()"使用 OrderedDict() 时自身打印