动态改变__slots__ [英] change __slots__ dynamically

查看:128
本文介绍了动态改变__slots__的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个类,需要给予它 __ dict __ 属性通过 __ init __ 注入像这样:

  class Torrent(Model):
def __init __(self,d):
super self).__ init __('torrents')
self .__ dict__ = d

确保不要更改对象的结构,因为实例将要在NOSQL数据库中结束。我认为 __ slots __ 可能有帮助,但我需要动态定义。



有办法



<$>

使用工厂函数:

p $ p> def GetTorrentClass(s​​lots_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可以是('field1','field2')

def save(self):
在self.fields中的字段:
self.store_to_db ,getattr(self,field))

这样,你确定只有你的实际字段保存到您的数据库。


I'm working on a class that needs to be given it's __dict__ attribute via __init__ injection like this:

class Torrent(Model):
    def __init__(self, d):
        super(Torrent, self).__init__('torrents')
        self.__dict__ = d

And need to make sure not to change the structure of the object because the instance is going to end up in a NOSQL db. I thought that __slots__ could be helpful, but I need to define it dynamically.

Is there a way to make it possible without a metaclass ?

解决方案

Use a factory function:

def GetTorrentClass(slots_iterable):
    class Torrent(object):
        __slots__ = slots_iterable
    return Torrent

Note that in order to use slots:

  • slots_iterable must be an iterable of strings
  • Your class must be new-style
  • Your class can't inherit a class that implements __dict__ (ie. that is not __slots__ only)

Now, you say you 'need to make sure not to change the structure of the object', using __slots__ is not the only (and probably not the best either) solution to your issue: using slots makes your class harder to use in code.

Instead, you could do the following:

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))

This way, you're sure that only your actual fields will be saved to your db.

这篇关于动态改变__slots__的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆