我正在处理一个类,需要给予它 __ dict __ 属性通过 __ init __ 注入像这样:
class Torrent(Model): def __init __(self,d): super self).__ init __('torrents') self .__ dict__ = d确保不要更改对象的结构,因为实例将要在NOSQL数据库中结束。我认为 __ slots __ 可能有帮助,但我需要动态定义。
有办法
使用工厂函数:
p $ p> 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可以是('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__ = dAnd 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 TorrentNote 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.
更多推荐
动态改变
发布评论