如何在Python中动态访问类属性? [英] How to dynamically access class properties in Python?

查看:396
本文介绍了如何在Python中动态访问类属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我创建了一个类的实例,并希望为其公共属性指定一些值。通常,这将是这样:

Let's say I create an instance of a class and want to assign some values to its public properties. Usually, this would be done like this:

class MyClass:
    def __init__(self):
        self.name = None
        self.text = None

myclass = MyClass()
myclass.name = 'My name'

但是,如果写一个函数接受一个类作为参数,我想为该类的公共属性动态分配一些值 - 是通过变量和循环(不知道有多少或它们被调用。)

But, what if a write a function that takes a class as parameter and I would like to assign some values to the public properties of that class dynamically - that is via variables and loops (without knowing how many there are or what they are called.)

显而易见的是:

myclass = MyClass()
myclass['name'] = "My name"

但这不行。

任何想法?

推荐答案

setattr(my_class_instance, 'attr_name', attr_value)

这篇关于如何在Python中动态访问类属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆