简体   繁体   中英

Python magic method for variable being accessed?

I am looking for a magic method similar to the __get__ method, but in my case the variable is not inside another class, I want something like:

class A(object):
  def __similar_to_get__(self):
    print 'called'
    return self

a = A()
b = a
>>> 'called'

Is it possible?

The reason I am asking this is, I am using a python mock library, let's say a function I am testing uses URI attribute, and I want to mock it to return different values in subsequent calls. Eg:

class WebService(obj):
  URI = 'http://works.com'

  def dowork(self):
     call_api(self.URI)

For me to mock a failure I am using the mock library:

 mock = MagicMock()
 mock.side_effect = ['http://fail.com', 'http://works.com']

 with patch('WebService.URI', mock):
     # do the testing

But the problem is I can only get mock to return the urls by calling the callable mock() not just simply accessing mock

PS: I am a mock noob.

Not directly answering my own question, I managed to use a property to work around this:

    from dps.px.pxpost import PxPost
    mock = MagicMock()
    mock.side_effect = ['http://doesnotexist', PxPost.URI]

    def URI(self):
        return mock()

    with patch('django.conf.settings.CELERY_ALWAYS_EAGER', True, create=True):
        with patch('dps.px.pxpost.PxPost.URI', property(URI)):
            self.transaction.process()
            for sub_transaction in self.transaction.sub_transactions.all():
                self.assertTrue(isinstance(sub_transaction.state, CompletedSubTransaction))
                self.assertTrue(sub_transaction.transaction_logs.count() > 0)
            self.assertTrue(isinstance(self.transaction.state, CompletedTransaction))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM