当前位置: 首页>>代码示例>>Python>>正文


Python ast.ClassDef方法代码示例

本文整理汇总了Python中ast.ClassDef方法的典型用法代码示例。如果您正苦于以下问题:Python ast.ClassDef方法的具体用法?Python ast.ClassDef怎么用?Python ast.ClassDef使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在ast的用法示例。


在下文中一共展示了ast.ClassDef方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: CONTINUE

# 需要导入模块: import ast [as 别名]
# 或者: from ast import ClassDef [as 别名]
def CONTINUE(self, node):
        # Walk the tree up until we see a loop (OK), a function or class
        # definition (not OK), for 'continue', a finally block (not OK), or
        # the top module scope (not OK)
        n = node
        while hasattr(n, 'parent'):
            n, n_child = n.parent, n
            if isinstance(n, LOOP_TYPES):
                # Doesn't apply unless it's in the loop itself
                if n_child not in n.orelse:
                    return
            if isinstance(n, (ast.FunctionDef, ast.ClassDef)):
                break
            # Handle Try/TryFinally difference in Python < and >= 3.3
            if hasattr(n, 'finalbody') and isinstance(node, ast.Continue):
                if n_child in n.finalbody:
                    self.report(messages.ContinueInFinally, node)
                    return
        if isinstance(node, ast.Continue):
            self.report(messages.ContinueOutsideLoop, node)
        else:  # ast.Break
            self.report(messages.BreakOutsideLoop, node) 
开发者ID:AtomLinter,项目名称:linter-pylama,代码行数:24,代码来源:checker.py

示例2: _visit_cls

# 需要导入模块: import ast [as 别名]
# 或者: from ast import ClassDef [as 别名]
def _visit_cls(self: 'ASTTagger', node: ast.ClassDef):
    bases = visit_suite(self.visit, node.bases)
    keywords = visit_suite(self.visit, node.keywords)
    decorator_list = visit_suite(self.visit, node.decorator_list)

    self.symtable.entered.add(node.name)

    new = self.symtable.enter_new()

    new.entered.add('__module__')
    new.entered.add('__qualname__')  # pep-3155 nested name.

    new_tagger = ASTTagger(new)
    new.cts.add(ContextType.ClassDef)
    body = visit_suite(new_tagger.visit, node.body)

    node.bases = bases
    node.keywords = keywords
    node.decorator_list = decorator_list
    node.body = body

    return Tag(node, new) 
开发者ID:Xython,项目名称:YAPyPy,代码行数:24,代码来源:symbol_analyzer.py

示例3: add_custom_type_symbol

# 需要导入模块: import ast [as 别名]
# 或者: from ast import ClassDef [as 别名]
def add_custom_type_symbol(self,
                               custom_type: ir2.CustomType,
                               definition_ast_node: Union[ast.ClassDef, ast.ImportFrom, None],
                               source_module: Optional[str] = None):
        self.add_symbol(name=custom_type.name,
                        expr_type=ir2.FunctionType(argtypes=tuple(arg.expr_type
                                                                  for arg in custom_type.arg_types),
                                                   argnames=tuple(arg.name
                                                                  for arg in custom_type.arg_types),
                                                   returns=custom_type),
                        definition_ast_node=definition_ast_node,
                        is_only_partially_defined=False,
                        is_function_that_may_throw=False)
        self.custom_types_symbol_table.add_symbol(name=custom_type.name,
                                                  expr_type=custom_type,
                                                  definition_ast_node=definition_ast_node,
                                                  is_only_partially_defined=False,
                                                  is_function_that_may_throw=False,
                                                  source_module=source_module) 
开发者ID:google,项目名称:tmppy,代码行数:21,代码来源:_ast_to_ir2.py

示例4: find_method

# 需要导入模块: import ast [as 别名]
# 或者: from ast import ClassDef [as 别名]
def find_method(module, namespace):
    """Filter away everything except the method

    Promote the method up to the global namespace so that it is
    indistinguishable from a regular function.

    Arguments:
        module (ast.Module): the entire parsed source code
        namespace (str): identifier for the method of interest

    Returns:
        module (ast.Module): the original module but with everything filtered
        away except the method name but with the name `namespace` and promoted
        to the global (i.e. top) level

    """
    module_name, class_name, method_name = namespace.split('.')
    classdefs = [stmt for stmt in module.body if isinstance(stmt, ast.ClassDef)]
    classdef, = [classdef for classdef in classdefs if classdef.name == class_name]
    methods = [stmt for stmt in classdef.body if isinstance(stmt, ast.FunctionDef)]
    for method in methods:
        if method.name == method_name:
            method.name = f'{module_name}.{class_name}.{method_name}'
            module.body = [method]
            return module 
开发者ID:ebanner,项目名称:pynt,代码行数:27,代码来源:syntax.py

示例5: classDefAtLineNumber

# 需要导入模块: import ast [as 别名]
# 或者: from ast import ClassDef [as 别名]
def classDefAtLineNumber(sourceAst, lineNumber):
    visitor = _AtLineNumberVisitor(lineNumber)
    visitor.visit(sourceAst)

    subnodesAtLineNumber = visitor.classDefSubnodesAtLineNumber

    if len(subnodesAtLineNumber) == 0:
        raise Exceptions.CantGetSourceTextError(
            "Can't find a ClassDef at line %s." % lineNumber
            )
    if len(subnodesAtLineNumber) > 1:
        raise Exceptions.CantGetSourceTextError(
            "Can't find a unique ClassDef at line %s." % lineNumber
            )

    return subnodesAtLineNumber[0] 
开发者ID:ufora,项目名称:ufora,代码行数:18,代码来源:PyAstUtil.py

示例6: _computeInitMethodAstOrNone

# 需要导入模块: import ast [as 别名]
# 或者: from ast import ClassDef [as 别名]
def _computeInitMethodAstOrNone(pyClassObject):
    pyAst = pyAstFor(pyClassObject)

    assert len(pyAst.body) == 1

    classDef = pyAst.body[0]

    assert isinstance(classDef, ast.ClassDef)

    tr = None

    # recall ClassDef = (identifier name, expr* bases, stmt* body, expr* decorator_list)
    # we're taking the *last* __init__ here
    for stmt in classDef.body:
        if isinstance(stmt, ast.FunctionDef) and stmt.name == "__init__":
            tr = stmt

    return tr 
开发者ID:ufora,项目名称:ufora,代码行数:20,代码来源:PyAstUtil.py

示例7: get_comments_str

# 需要导入模块: import ast [as 别名]
# 或者: from ast import ClassDef [as 别名]
def get_comments_str(file_name):
    with open(file_name) as fd:
        file_contents = fd.read()
    module = ast.parse(file_contents)

    function_definitions = [node for node in module.body if isinstance(node, ast.FunctionDef)]

    doc = get_func_comments(function_definitions)

    class_definitions = [node for node in module.body if isinstance(node, ast.ClassDef)]
    for class_def in class_definitions:
        temp_str = to_md(parse_func_string(ast.get_docstring(class_def)))

        # excludes private methods (start with '_')
        method_definitions = [
            node
            for node in class_def.body
            if isinstance(node, ast.FunctionDef) and (node.name[0] != '_' or node.name[:2] == '__')
        ]

        temp_str += get_func_comments(method_definitions)
        doc += '## class ' + class_def.name + '\n' + temp_str
    return doc 
开发者ID:idealo,项目名称:image-quality-assessment,代码行数:25,代码来源:autogen.py

示例8: find_globals

# 需要导入模块: import ast [as 别名]
# 或者: from ast import ClassDef [as 别名]
def find_globals(g, tree):
    """Uses AST to find globals in an ast tree"""
    for child in tree:
        if hasattr(child, 'body') and isinstance(child.body, list):
            find_globals(g, child.body)
        elif isinstance(child, (ast.FunctionDef, ast.ClassDef)):
            g.add(child.name)
            continue
        elif isinstance(child, ast.Assign):
            try:
                g.add(child.targets[0].id)
            except (IndexError, AttributeError):
                pass
        elif isinstance(child, ast.Import):
            g.add(child.names[0].name)
        elif isinstance(child, ast.ImportFrom):
            for name in child.names:
                g_name = name.asname or name.name
                if g_name == '*':
                    continue
                g.add(g_name) 
开发者ID:sivel,项目名称:ansible-testing,代码行数:23,代码来源:utils.py

示例9: test_classdef

# 需要导入模块: import ast [as 别名]
# 或者: from ast import ClassDef [as 别名]
def test_classdef(self):
        def cls(bases=None, keywords=None, body=None, decorator_list=None):
            if bases is None:
                bases = []
            if keywords is None:
                keywords = []
            if body is None:
                body = [ast.Pass()]
            if decorator_list is None:
                decorator_list = []
            return ast.ClassDef("myclass", bases, keywords,
                                body, decorator_list)
        self.stmt(cls(bases=[ast.Name("x", ast.Store())]),
                  "must have Load context")
        self.stmt(cls(keywords=[ast.keyword("x", ast.Name("x", ast.Store()))]),
                  "must have Load context")
        self.stmt(cls(body=[]), "empty body on ClassDef")
        self.stmt(cls(body=[None]), "None disallowed")
        self.stmt(cls(decorator_list=[ast.Name("x", ast.Store())]),
                  "must have Load context") 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:22,代码来源:test_ast.py

示例10: parse_functions

# 需要导入模块: import ast [as 别名]
# 或者: from ast import ClassDef [as 别名]
def parse_functions(code):
    """Parse all the global functions present in the input code.

    Parse all the ast nodes ast.FunctionDef that are global functions in the
    source code. These also include function that are defined inside other
    Python statements, like `try`. ast.ClassDef nodes are skipped from the
    parsing so that class functions are ignored.

    Args:
        code (str): Multiline string representing Python code

    Returns (dict): A dictionary [fn_name] -> function_source
    """
    fns = dict()
    tree = ast.parse(code)
    for block in tree.body:
        for node in walk(block,
                         stop_at=(ast.FunctionDef,),
                         ignore=(ast.ClassDef,)):
            if isinstance(node, (ast.FunctionDef,)):
                fn_name = node.name
                fns[fn_name] = astor.to_source(node)
    return fns 
开发者ID:kubeflow-kale,项目名称:kale,代码行数:25,代码来源:ast.py

示例11: get_function_and_class_names

# 需要导入模块: import ast [as 别名]
# 或者: from ast import ClassDef [as 别名]
def get_function_and_class_names(code):
    """Get all function and class names of the code block.

    Inspects the code walking through its AST and returns all
    the names of nodes matching ast.FunctionDef or ast.ClassDef.

    Args:
        code: Multiline string representing Python code

    Returns: List of string names
    """
    names = set()
    tree = ast.parse(code)
    for block in tree.body:
        for node in walk(block):
            if isinstance(node, (ast.FunctionDef, ast.ClassDef,)):
                names.add(node.name)
    return names 
开发者ID:kubeflow-kale,项目名称:kale,代码行数:20,代码来源:ast.py

示例12: test_classdef

# 需要导入模块: import ast [as 别名]
# 或者: from ast import ClassDef [as 别名]
def test_classdef(self):
        def cls(bases=None, keywords=None, starargs=None, kwargs=None,
                body=None, decorator_list=None):
            if bases is None:
                bases = []
            if keywords is None:
                keywords = []
            if body is None:
                body = [ast.Pass()]
            if decorator_list is None:
                decorator_list = []
            return ast.ClassDef("myclass", bases, keywords, starargs,
                                kwargs, body, decorator_list)
        self.stmt(cls(bases=[ast.Name("x", ast.Store())]),
                  "must have Load context")
        self.stmt(cls(keywords=[ast.keyword("x", ast.Name("x", ast.Store()))]),
                  "must have Load context")
        self.stmt(cls(starargs=ast.Name("x", ast.Store())),
                  "must have Load context")
        self.stmt(cls(kwargs=ast.Name("x", ast.Store())),
                  "must have Load context")
        self.stmt(cls(body=[]), "empty body on ClassDef")
        self.stmt(cls(body=[None]), "None disallowed")
        self.stmt(cls(decorator_list=[ast.Name("x", ast.Store())]),
                  "must have Load context") 
开发者ID:IronLanguages,项目名称:ironpython3,代码行数:27,代码来源:test_ast.py

示例13: CONTINUE

# 需要导入模块: import ast [as 别名]
# 或者: from ast import ClassDef [as 别名]
def CONTINUE(self, node):
        # Walk the tree up until we see a loop (OK), a function or class
        # definition (not OK), for 'continue', a finally block (not OK), or
        # the top module scope (not OK)
        n = node
        while hasattr(n, '_pyflakes_parent'):
            n, n_child = n._pyflakes_parent, n
            if isinstance(n, LOOP_TYPES):
                # Doesn't apply unless it's in the loop itself
                if n_child not in n.orelse:
                    return
            if isinstance(n, (ast.FunctionDef, ast.ClassDef)):
                break
            # Handle Try/TryFinally difference in Python < and >= 3.3
            if hasattr(n, 'finalbody') and isinstance(node, ast.Continue):
                if n_child in n.finalbody and not PY38_PLUS:
                    self.report(messages.ContinueInFinally, node)
                    return
        if isinstance(node, ast.Continue):
            self.report(messages.ContinueOutsideLoop, node)
        else:  # ast.Break
            self.report(messages.BreakOutsideLoop, node) 
开发者ID:PyCQA,项目名称:pyflakes,代码行数:24,代码来源:checker.py

示例14: _generate_nodes

# 需要导入模块: import ast [as 别名]
# 或者: from ast import ClassDef [as 别名]
def _generate_nodes(parent, level=0, breadcrumb=''):
        nodes = []

        for child in parent.body:
            if isinstance(child, ast.ClassDef):
                style = OutlineNodeItem.Style.cls
            elif isinstance(child, ast.FunctionDef) or isinstance(child, ast.AsyncFunctionDef):
                style = OutlineNodeItem.Style.fn
            else:
                style = None

            if style:
                node = OutlineNodeItem(style, child.name, child.lineno, child.col_offset, level, breadcrumb)
                nodes.append(node)
                if breadcrumb:
                    bc = '{} • {}'.format(breadcrumb, child.name)
                else:
                    bc = child.name
                child_nodes = OutlineDataSource._generate_nodes(child, level + 1, bc)
                if child_nodes:
                    nodes.extend(child_nodes)

        return nodes 
开发者ID:zrzka,项目名称:blackmamba,代码行数:25,代码来源:outline_quickly.py

示例15: _main_frame

# 需要导入模块: import ast [as 别名]
# 或者: from ast import ClassDef [as 别名]
def _main_frame(self, node):
        # type: (ast.AST) -> Optional[FrameType]
        frame = sys._getframe(2)
        result = self.secondary_to_main_frames.get(frame)
        if result:
            return result

        original_frame = frame

        while frame.f_code.co_name in ('<listcomp>', '<dictcomp>', '<setcomp>'):
            frame = frame.f_back

        for node in ancestors(node):
            if isinstance(node, (ast.FunctionDef, ast.Lambda)):
                break

            if isinstance(node, ast.ClassDef):
                frame = frame.f_back

        if frame.f_code.co_name in ('<lambda>', '<genexpr>'):
            return None

        self.secondary_to_main_frames[original_frame] = frame
        self.main_to_secondary_frames[frame].append(original_frame)
        return frame 
开发者ID:alexmojaki,项目名称:executing,代码行数:27,代码来源:tracer.py


注:本文中的ast.ClassDef方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。