python - python 中当前字符串如何作为对象属性?

标签 python

我有一个有趣的问题。我有类(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 to x.foobar = 123.

关于python - python 中当前字符串如何作为对象属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43263050/

相关文章:

python Pandas : groupby on two columns and create new variables

python - 从 GtkDialog 上的 Gtk.TreeView 激活 default_button (python/Gtk3)

python - 在我的函数中用括号混淆了 bug

Python 类继承 multiprocessing : mocking one of the class objects

Python:dataframe的索引是三列的组合,如何将它们分开?

python - Catboost 的 verbose 可以是 int 吗?

python - 查找允许某些不匹配的子字符串的快速方法

python - PySide (1.1.2)、cx_freeze、WinXP、Python 3.3 : ImportError: DLL load failed

python - 重新打开 GTK 窗口后无法访问文本输入框

python - 代码 '_T = TypeVar(' _T')' 在 *.pyi 文件中是什么意思?