Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
127 views
in Technique[技术] by (71.8m points)

How to dynamically access class properties in 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.)

The obvious would be:

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

But that doesn't work.

Any ideas?

question from:https://stackoverflow.com/questions/2425272/how-to-dynamically-access-class-properties-in-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
setattr(my_class_instance, 'attr_name', attr_value)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...