Python - 直接嵌套函数调用

Python - Direct nested function call

我想直接调用嵌套函数,像这样:

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

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

我试过这个:

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

但我收到以下错误:

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

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

如何在 Python 中实现?

您必须 return 一个提供 to_be_in 函数成员的对象,即(仅示例):

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)