Is it possible to create anonymous objects in Python?

前端 未结 11 583
余生分开走
余生分开走 2020-12-14 13:58

I\'m debugging some Python that takes, as input, a list of objects, each with some attributes.

I\'d like to hard-code some test values -- let\'s say, a list of four

相关标签:
11条回答
  • 2020-12-14 14:37

    I will use lambda

    obj = lambda: None
    obj.s = 'abb'
    obj.i = 122
    
    0 讨论(0)
  • 2020-12-14 14:38

    Have a look at this:

    
    class MiniMock(object):
        def __new__(cls, **attrs):
            result = object.__new__(cls)
            result.__dict__ = attrs
            return result
    
    def print_foo(x):
        print x.foo
    
    print_foo(MiniMock(foo=3))
    
    0 讨论(0)
  • 2020-12-14 14:45

    Another obvious hack:

    class foo1: x=3; y='y'
    class foo2: y=5; x=6
    
    print(foo1.x, foo2.y)
    

    But for your exact usecase, calling a function with anonymous objects directly, I don't know any one-liner less verbose than

    myfunc(type('', (object,), {'foo': 3},), type('', (object,), {'foo': 4}))
    

    Ugly, does the job, but not really.

    0 讨论(0)
  • 2020-12-14 14:47

    I like Tetha's solution, but it's unnecessarily complex.

    Here's something simpler:

    >>> class MicroMock(object):
    ...     def __init__(self, **kwargs):
    ...         self.__dict__.update(kwargs)
    ...
    >>> def print_foo(x):
    ...     print x.foo
    ...
    >>> print_foo(MicroMock(foo=3))
    3
    
    0 讨论(0)
  • 2020-12-14 14:47

    Maybe you can use namedtuple to solve this as following:

    from collections import namedtuple
    Mock = namedtuple('Mock', ['foo'])
    
    mock = Mock(foo=1)
    mock.foo  // 1
    
    0 讨论(0)
提交回复
热议问题