我正在上一门课,需要提供它__dict__
属性通过__init__
像这样注入:
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
必须是字符串的可迭代对象
- 你的班级一定是新式的
- 您的类不能继承实现的类
__dict__
(即,这不是__slots__
only)
现在,你说你“需要确保不改变对象的结构”,使用__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))
这样,您就可以确定只有您的实际字段才会保存到您的数据库中。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)