我有一个有趣的问题。我有类(class)模型:
class Patient(models.Model):
separation = models.ForeignKey(Separation, blank=True,
null=True, default=None)
number_card = models.IntegerField(default=0)
我可以写:
patient = Patient()
patient.name = 'Saney'
但是如果我不知道必须更改哪些属性,我该怎么办。例如,必须更改的属性名称位于变量“property='name'”中。但如果我写下一个代码:
patient.property = 'Saney'
python 不明白我的意思是我想将“Saney”写入 Patient.name 而不是 Patient.property。当我尝试测试某些东西时,例如:
patient.'name'= 'Saney'
python 当然给出了一个错误...)
最佳答案
您可以使用setattr(..)
为此:
setattr(patient,'name','Saney')
这相当于:
patient.name = 'Saney'
setattr(..)
内置函数具有以下结构:
setattr(object, name, value)
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 tox.foobar = 123
.
关于python - python 中当前字符串如何作为对象属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43263050/