简体   繁体   中英

Python - Direct nested function call

I want to call a nested function directly, like this:

Template('/path/to/file').expect('key').to_be_in('second_key')

Template('/path/to/file').expect('key').to_be('value')

I tried this:

class Template(object):
  def __init__(self, path):
    self.content = json.load(open(path, 'r'))

  def expect(self, a):
    def to_be_in(b):
      b = self.content[b]
      return a in b

    def to_be(b):
      a = self.content[b]
      return a == b

But I get the following error:

Template('~/template.json').expect('template_name').to_be_in('domains')

AttributeError: 'NoneType' object has no attribute 'to_be_in'

How to achieve that in Python ?

You have to return an object which provides a to_be_in member that is a function, to wit (example only):

class Template_Expect(object):
    def __init__(self, template, a):
        self.template = template
        self.a = a

    def to_be_in(self, b):
        b = self.template.content[b]
        return self.a in b

    def to_be(self, b):
        a = self.template.content[b]
        return a == b

class Template(object):
    def __init__(self, path):
        self.content = json.load(open(path, 'r'))

    def expect(self, a):
        return Template_Expect(self, a)

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