This is the counterpart of getattr(). The arguments are an object, a
string and an arbitrary value. The string may name an existing
attribute or a new attribute. The function assigns the value to the
attribute, provided the object allows it. For example, setattr(x,
'foobar', 123) is equivalent to x.foobar = 123.
您可以这样做:
class Joint:
spineX = 0.0
spineY = 0.0
spineZ = 0.0
s = '{"spineX":8.9,"spineY":7.7,"spineZ":9.9}'
o = json.loads(s)
for k in o.keys():
setattr(Joint, k, o[k])
print(Joint.spineX)
print(Joint.spineY)
print(Joint.spineZ)
输出:
8.9
7.7
9.9
现在,Joint的每个新实例都将具有这些class attribute值。如果您这样做:
x = Joint()
print(x.spineX)
print(x.spineY)
print(x.spineZ)
好吧,我要附加这个答案,因为你说的是
class attributes
,而不是instance attributes
。您可以使用built-in functionsetattr
:您可以这样做:
输出:
现在,
Joint
的每个新实例都将具有这些class attribute
值。如果您这样做:您还将获得:
更有趣的是,使用
setattr()
甚至可以添加尚未定义的class attributes
。例如:将输出:
也许可以在类中添加
__init__
:相关问题 更多 >
编程相关推荐