Python Language Question: attributes of object() vs Function

后端 未结 4 1108
南方客
南方客 2020-12-14 10:02

In python, it is illegal to create new attribute for an object instance like this

>>> a = object()
>>> a.hhh = 1

throws <

4条回答
  •  孤城傲影
    2020-12-14 10:45

    Alex Martelli posted an awesome answer to your question. For anyone who is looking for a good way to accomplish arbitrary attributes on an empty object, do this:

    class myobject(object):
        pass
    
    o = myobject()
    o.anything = 123
    

    Or more efficient (and better documented) if you know the attributes:

    class myobject(object):
        __slots__ = ('anything', 'anythingelse')
    
    o = myobject()
    o.anything = 123
    o.anythingelse = 456
    

提交回复
热议问题