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

前端 未结 16 1693
长情又很酷
长情又很酷 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 00:54

    You can also use a class object directly; it creates a namespace:

    class a: pass
    a.somefield1 = 'somevalue1'
    setattr(a, 'somefield2', 'somevalue2')
    
    0 讨论(0)
  • 2020-11-28 00:56

    There are a few ways to reach this goal. Basically you need an object which is extendable.

    obj.a = type('Test', (object,), {})  
    obj.a.b = 'fun'  
    
    obj.b = lambda:None
    
    class Test:
      pass
    obj.c = Test()
    
    0 讨论(0)
  • 2020-11-28 00:57

    Try the code below:

    $ python
    >>> class Container(object):
    ...     pass 
    ...
    >>> x = Container()
    >>> x.a = 10
    >>> x.b = 20
    >>> x.banana = 100
    >>> x.a, x.b, x.banana
    (10, 20, 100)
    >>> dir(x)
    ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', 
    '__getattribute__', '__hash__', '__init__', '__module__', '__new__',
    '__reduce__', '__reduce_ex__', '__repr__', '__setattr__',     '__sizeof__', 
    '__str__', '__subclasshook__', '__weakref__', 'a', 'b', 'banana']
    
    0 讨论(0)
  • 2020-11-28 01:00

    I think the easiest way is through the collections module.

    import collections
    FinanceCtaCteM = collections.namedtuple('FinanceCtaCte', 'forma_pago doc_pago get_total')
    def get_total(): return 98989898
    financtacteobj = FinanceCtaCteM(forma_pago='CONTADO', doc_pago='EFECTIVO',
                                    get_total=get_total)
    
    print financtacteobj.get_total()
    print financtacteobj.forma_pago
    print financtacteobj.doc_pago
    
    0 讨论(0)
  • 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')
    
    0 讨论(0)
  • 2020-11-28 01:05

    Other way i see, this way:

    import maya.cmds
    
    def getData(objets=None, attrs=None):
        di = {}
        for obj in objets:
            name = str(obj)
            di[name]=[]
            for at in attrs:
                di[name].append(cmds.getAttr(name+'.'+at)[0])
        return di
    
    acns=cmds.ls('L_vest_*_',type='aimConstraint')
    attrs=['offset','aimVector','upVector','worldUpVector']
    
    getData(acns,attrs)
    
    0 讨论(0)
提交回复
热议问题