python闭包问题源代码编译器

2024-06-24 13:49:11 发布

您现在位置:Python中文网/ 问答频道 /正文

此代码是从http://code.google.com/p/closure-library/source/browse/trunk/closure/bin/build/source.py复制的

源类的\uu str __方法引用自身。\路径

它是属于自己的特殊财产吗?在

因为,我找不到在源类定义这个变量的地方

import re

_BASE_REGEX_STRING = '^\s*goog\.%s\(\s*[\'"](.+)[\'"]\s*\)'
_PROVIDE_REGEX = re.compile(_BASE_REGEX_STRING % 'provide')
_REQUIRES_REGEX = re.compile(_BASE_REGEX_STRING % 'require')

# This line identifies base.js and should match the line in that file.
_GOOG_BASE_LINE = (
    'var goog = goog || {}; // Identifies this file as the Closure base.')


class Source(object):
  """Scans a JavaScript source for its provided and required namespaces."""

  def __init__(self, source):
    """Initialize a source.

    Args:
      source: str, The JavaScript source.
    """

    self.provides = set()
    self.requires = set()

    self._source = source
    self._ScanSource()

  def __str__(self):
    return 'Source %s' % self._path #!!!!!! what is self_path !!!!

  def GetSource(self):
    """Get the source as a string."""
    return self._source

  def _ScanSource(self):
    """Fill in provides and requires by scanning the source."""

    # TODO: Strip source comments first, as these might be in a comment
    # block.  RegExes can be borrowed from other projects.
    source = self.GetSource()

    source_lines = source.splitlines()
    for line in source_lines:
      match = _PROVIDE_REGEX.match(line)
      if match:
        self.provides.add(match.group(1))
      match = _REQUIRES_REGEX.match(line)
      if match:
        self.requires.add(match.group(1))

    # Closure's base file implicitly provides 'goog'.
    for line in source_lines:
      if line == _GOOG_BASE_LINE:
        if len(self.provides) or len(self.requires):
          raise Exception(
              'Base files should not provide or require namespaces.')
        self.provides.add('goog')


def GetFileContents(path):
  """Get a file's contents as a string.

  Args:
    path: str, Path to file.

  Returns:
    str, Contents of file.

  Raises:
    IOError: An error occurred opening or reading the file.

  """
  fileobj = open(path)
  try:
    return fileobj.read()
  finally:
    fileobj.close()

Tags: thepathinselfsourcebasedefas
1条回答
网友
1楼 · 发布于 2024-06-24 13:49:11

不,_path只是一个属性,与其他属性一样,它可以也不可以设置在对象上。前导下划线只是意味着作者认为它是对象的内部细节,不希望它被视为公共接口的一部分。在

在这种特殊情况下,除非有人从源文件外部设置属性,否则看起来这只是一个错误。除非有人试图对Source对象调用str(),而且可能没有人这样做,否则它不会造成任何伤害。在

顺便说一句,你似乎认为self有什么特别之处。名称self在任何方面都不是特殊的:将此名称用于方法的第一个参数是一种惯例,但它只是一个与其他名称类似的名称,它引用正在处理的对象。因此,如果您可以访问self._path而不引起错误,那么您可以通过对象的任何其他名称来访问它。在

相关问题 更多 >