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

前端 未结 16 1735
长情又很酷
长情又很酷 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:03

    If we can determine and aggregate all the attributes and values together before creating the nested object, then we could create a new class that takes a dictionary argument on creation.

    # python 2.7
    
    class NestedObject():
        def __init__(self, initial_attrs):
            for key in initial_attrs:
                setattr(self, key, initial_attrs[key])
    
    obj = someobject
    attributes = { 'attr1': 'val1', 'attr2': 'val2', 'attr3': 'val3' }
    obj.a = NestedObject(attributes)
    >>> obj.a.attr1
    'val1'
    >>> obj.a.attr2
    'val2'
    >>> obj.a.attr3
    'val3'
    

    We can also allow keyword arguments. See this post.

    class NestedObject(object):
        def __init__(self, *initial_attrs, **kwargs):
            for dictionary in initial_attrs:
                for key in dictionary:
                    setattr(self, key, dictionary[key])
            for key in kwargs:
                setattr(self, key, kwargs[key])
    
    
    obj.a = NestedObject(attr1='val1', attr2='val2', attr3= 'val3')
    

提交回复
热议问题