Is it possible to create anonymous objects in Python?

前端 未结 11 582
余生分开走
余生分开走 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:20
    anonymous_object = type('',(),{'name':'woody', 'age':'25'})()
    anonymous_object.name
    > 'woody'
    

    There is a cool way but hard to understand. It use type() create a no-named class with default init params, then init it without any param and get the anonymous object.

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

    I found this: http://www.hydrogen18.com/blog/python-anonymous-objects.html, and in my limited testing it seems like it works:

    >>> obj = type('',(object,),{"foo": 1})()
    >>> obj.foo
    1
    
    0 讨论(0)
  • 2020-12-14 14:29

    So brief, such Python! O.o

    >>> Object = lambda **kwargs: type("Object", (), kwargs)
    

    Then you can use Object as a generic object constructor:

    >>> person = Object(name = "Bernhard", gender = "male", age = 42)
    >>> person.name
    'Bernhard'
    >>>
    

    EDIT: Well okay, technically this creates a class object, not an object object. But you can treat it like an anonymous object or you modify the first line by appending a pair of parenthesis to create an instance immediately:

    >>> Object = lambda **kwargs: type("Object", (), kwargs)()
    
    0 讨论(0)
  • 2020-12-14 14:35

    As of Python 3.3, there's types.SimpleNamespace that does exactly what you want:

    myfunc([types.SimpleNamespace(foo=1), types.SimpleNamespace(foo=2), types.SimpleNamespace(foo=3), types.SimpleNamespace(foo=4)])
    

    That's a tad wordy, but you can clean it up with an alias:

    _ = types.SimpleNamespace
    myfunc([_(foo=1), _(foo=2), _(foo=3), _(foo=4)])
    

    And now that's actually pretty close to the fictional syntax in your question.

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

    This is how I did it:

    from mock import patch
    import requests
    
    class MockResponse:
    
        def __init__(self, text, status_code):
            self.text = text
            self.status_code = status_code
    
    
    class TestSomething(unittest.TestCase):
    
        @patch('requests.get',return_value=MockResponse('the result',200))
        def test_some_request(self, *args, **kwargs):
            response = requests.get('some.url.com')
            assert response.text=='the result'
            assert response.status_code=='200'
    
    0 讨论(0)
  • 2020-12-14 14:37

    Non classy:

    def mock(**attrs):
        r = lambda:0
        r.__dict__ = attrs
        return r 
    
    def test(a, b, c, d):
        print a.foo, b.foo, c.foo, d.foo
    
    test(*[mock(foo=i) for i in xrange(1,5)])
    # or
    test(mock(foo=1), mock(foo=2), mock(foo=3), mock(foo=4))
    
    0 讨论(0)
提交回复
热议问题