使用self.__dict__修改模型类
我偶然发现了一些用Python写的代码,它实现了一个REST API,这个API可以对一个类进行操作,比如获取和设置属性,代码大概是这样的:
class Model(
def __init__(self, foo=1, bar=0, baz=0):
self.foo = foo
self.bar = bar
self.baz = baz
def get_api(self):
return self.__dict__.keys()
def set_parameters(self, parameters):
for p in parameters.keys():
if p in self.__dict__.keys():
self.__dict__[p] = parameters[p]
简单来说,这个REST API是通过get_api()
来“构建”的,所以它和类的实例属性一一对应。
在Python的世界里,这算是“好习惯”吗?(我觉得看起来有点像是临时拼凑的)
如果不是,那有什么更好的方法来在类中存储模型呢?
1 个回答
0
你用的方法没问题,但有一些术语用错了:
self.foo
等是实例
属性——也就是说,你只能在Model
的实例上看到它们:
>>> Model.foo # class access
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: type object 'Model' has no attribute 'foo'
>>> m = Model() # create an instance
>>> m.foo # instance access
1
properties
是非常特定类型的属性:简单来说,它们是由代码支持的数据片段(这个回答有更多细节)。