Home >Backend Development >Python Tutorial >How Can I Dynamically Set Attributes in Python Objects?

How Can I Dynamically Set Attributes in Python Objects?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-01 14:39:17579browse

How Can I Dynamically Set Attributes in Python Objects?

Setting Attributes Dynamically in Python

Suppose you have a Python object x and a string s. How do you programmatically set the attribute s on x such that the attribute can be accessed as x.myAttr?

To accomplish this, you can utilize the setattr() built-in function, which has the following syntax:

setattr(object, name, value)

In this specific scenario, you would use it as follows:

setattr(x, attr, 'magic')

This effectively sets the attribute attr on the object x to the value 'magic'. As a result, you can now access this attribute through x.myAttr.

It's important to note that this approach can be particularly useful for caching calls to x.__getattr__(). Keep in mind, however, that you cannot directly apply this method to a pure instance of object. Instead, it is more commonly applied to custom subclasses of object.

The above is the detailed content of How Can I Dynamically Set Attributes in Python Objects?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn