我正在开发一个需要通过 __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/