How can I create an object and add attributes to it?

前端 未结 16 1695
长情又很酷
长情又很酷 2020-11-28 00:36

I want to create a dynamic object (inside another object) in Python and then add attributes to it.

I tried:

obj = someobject
obj.a = object()
setattr         


        
相关标签:
16条回答
  • 2020-11-28 01:16

    There is types.SimpleNamespace class in Python 3.3+:

    obj = someobject
    obj.a = SimpleNamespace()
    for p in params:
        setattr(obj.a, p, value)
    # obj.a.attr1
    

    collections.namedtuple, typing.NamedTuple could be used for immutable objects. PEP 557 -- Data Classes suggests a mutable alternative.

    For a richer functionality, you could try attrs package. See an example usage.

    0 讨论(0)
  • 2020-11-28 01:16

    The mock module is basically made for that.

    import mock
    obj = mock.Mock()
    obj.a = 5
    
    0 讨论(0)
  • 2020-11-28 01:16

    Which objects are you using? Just tried that with a sample class and it worked fine:

    class MyClass:
      i = 123456
      def f(self):
        return "hello world"
    
    b = MyClass()
    b.c = MyClass()
    setattr(b.c, 'test', 123)
    b.c.test
    

    And I got 123 as the answer.

    The only situation where I see this failing is if you're trying a setattr on a builtin object.

    Update: From the comment this is a repetition of: Why can't you add attributes to object in python?

    0 讨论(0)
  • 2020-11-28 01:17

    Now you can do (not sure if it's the same answer as evilpie):

    MyObject = type('MyObject', (object,), {})
    obj = MyObject()
    obj.value = 42
    
    0 讨论(0)
提交回复
热议问题