简体   繁体   English

变量被访问的Python魔术方法?

[英]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: 我正在寻找一个类似于__get__方法的__get__方法,但在我的情况下,变量不在另一个类中,我想要类似的东西:

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. 我问这个的原因是,我正在使用python模拟库,假设我正在测试的函数使用URI属性,我想模拟它以在后续调用中返回不同的值。 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 但问题是我只能通过调用可调用的mock()而不仅仅是访问mock来获得mock来返回url

PS: I am a mock noob. PS:我是一个模拟菜鸟。

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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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