How to dynamically access class properties in Python?

后端 未结 3 546
广开言路
广开言路 2020-12-03 09:44

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:
            


        
相关标签:
3条回答
  • 2020-12-03 10:13

    Using dir with setattr should do the job

    class MyClass:
      def __init__(self):
        self.name = None
        self.text = None
    
    myclass = MyClass()
    myclass.name = 'My name'
    
    for prop in dir(myclass):
        print '%s:%s'%(prop,getattr(myclass,prop))
    
    print
    
    for prop in dir(myclass):
        if prop[:2]!='__' and prop[-2:]!='__':
            print prop[-2:]
            setattr(myclass,prop,"Foo Bar")
    
    for prop in dir(myclass):
        print '%s:%s'%(prop,getattr(myclass,prop))    
    

    But be careful because this code also sets '__doc__', '__init__', '__module__' properties to "Foo Bar". So you will have to take care of avoiding certain things given to you by dir (especially those which start and end with __ double underscores).

    0 讨论(0)
  • 2020-12-03 10:21
    setattr(my_class_instance, 'attr_name', attr_value)
    
    0 讨论(0)
  • 2020-12-03 10:24

    After reading rejected Syntax For Dynamic Attribute Access I'm using a mixin class providing dictionary-style access to an object's attributes :

    class MyClass:
        def __init__(self):
            self.name = None
            self.text = None
        def __getitem__(self, name):
            return getattr(self, name)
        def __setitem__(self, name, value):
            return setattr(self, name, value)
        def __delitem__(self, name):
            return delattr(self, name)
        def __contains__(self, name):
            return hasattr(self, name)
    

    While still being able to set attributes directly:

    myclass = MyClass()
    myclass.name = "foo"
    myclass.text = "bar"
    

    it's then possible to set them dynamically :

    for attr in ('name', 'text'):
        myclass[attr] = confirm(attr, default=myclass[attr])
    
    0 讨论(0)
提交回复
热议问题