动态改变

编程入门 行业动态 更新时间:2024-10-27 01:20:51
本文介绍了动态改变__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.

更多推荐

动态改变

本文发布于:2023-07-04 10:09:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1023082.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:动态

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!