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


Python types.new_class方法代码示例

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


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

示例1: _new_nonterm

# 需要导入模块: import types [as 别名]
# 或者: from types import new_class [as 别名]
def _new_nonterm(self, clsname, clsdict=None, clskwds=None,
                     clsbases=(Nonterm,)):
        if clsdict is None:
            clsdict = {}
        if clskwds is None:
            clskwds = {}
        mod = sys.modules[self.name]

        def clsexec(ns):
            ns['__module__'] = self.name
            for k, v in clsdict.items():
                ns[k] = v
            return ns

        cls = types.new_class(clsname, clsbases, clskwds, clsexec)
        setattr(mod, clsname, cls)
        return cls 
开发者ID:edgedb,项目名称:edgedb,代码行数:19,代码来源:commondl.py

示例2: mk_bitstruct

# 需要导入模块: import types [as 别名]
# 或者: from types import new_class [as 别名]
def mk_bitstruct( cls_name, fields, *, namespace=None, add_init=True,
                   add_str=True, add_repr=True, add_hash=True ):

  # copy namespace since  will mutate it
  namespace = {} if namespace is None else namespace.copy()

  # We assume fields is a dictionary and thus there won't be duplicate
  # field names. So we only check if the field names are indeed strings
  # and that they are not keywords.
  annos = {}
  for name, f in fields.items():
    if not isinstance( name, str ) or not name.isidentifier():
      raise TypeError( f'Field name {name!r} is not a valid identifier!' )
    if keyword.iskeyword( name ):
      raise TypeError( f'Field name {name!r} is a keyword!' )
    annos[ name ] = f

  namespace['__annotations__'] = annos
  cls = types.new_class( cls_name, (), {}, lambda ns: ns.update( namespace ) )
  return bitstruct( cls, add_init=add_init, add_str=add_str,
                    add_repr=add_repr, add_hash=add_hash ) 
开发者ID:pymtl,项目名称:pymtl3,代码行数:23,代码来源:bitstructs.py

示例3: patch_config_as_nothrow

# 需要导入模块: import types [as 别名]
# 或者: from types import new_class [as 别名]
def patch_config_as_nothrow(instance):
    if "NoThrow" in [instance.__name__, instance.__class__.__name__]:
        return instance

    if type(instance) == type:
        instance = types.new_class(instance.__name__ + "NoThrow", (instance, ), dict(metaclass=NoThrowMeta))
        for (k, v) in inspect.getmembers(instance):
            if not k.startswith("__") and type(v) == type:
                type.__setattr__(instance, k, patch_config_as_nothrow(v))
    else:
        for (k, v) in inspect.getmembers(instance.__class__):
            if not k.startswith("__") and type(v) == type:
                type.__setattr__(instance.__class__, k, patch_config_as_nothrow(v))
        instance.__class__ = type(instance.__class__.__name__ + "NoThrow", (instance.__class__, NoThrowBase), {})

    return instance 
开发者ID:TuSimple,项目名称:simpledet,代码行数:18,代码来源:patch_config.py

示例4: test_prepare_class

# 需要导入模块: import types [as 别名]
# 或者: from types import new_class [as 别名]
def test_prepare_class(self):
        # Basic test of metaclass derivation
        expected_ns = {}
        class A(type):
            def __new__(*args, **kwargs):
                return type.__new__(*args, **kwargs)

            def __prepare__(*args):
                return expected_ns

        B = types.new_class("B", (object,))
        C = types.new_class("C", (object,), {"metaclass": A})

        # The most derived metaclass of D is A rather than type.
        meta, ns, kwds = types.prepare_class("D", (B, C), {"metaclass": type})
        self.assertIs(meta, A)
        self.assertIs(ns, expected_ns)
        self.assertEqual(len(kwds), 0) 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:20,代码来源:test_types.py

示例5: test_metaclass_override_function

# 需要导入模块: import types [as 别名]
# 或者: from types import new_class [as 别名]
def test_metaclass_override_function(self):
        # Special case: the given metaclass isn't a class,
        # so there is no metaclass calculation.
        class A(metaclass=self.Meta):
            pass

        marker = object()
        def func(*args, **kwargs):
            return marker

        X = types.new_class("X", (), {"metaclass": func})
        Y = types.new_class("Y", (object,), {"metaclass": func})
        Z = types.new_class("Z", (A,), {"metaclass": func})
        self.assertIs(marker, X)
        self.assertIs(marker, Y)
        self.assertIs(marker, Z) 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:18,代码来源:test_types.py

示例6: specialize_class

# 需要导入模块: import types [as 别名]
# 或者: from types import new_class [as 别名]
def specialize_class(cls, kind, base=None, **kwargs):
    # XXX Support passing in submodule names--load (and cache) them?
    # That would clean up the test modules a bit more.
    if base is None:
        base = unittest.TestCase
    elif not isinstance(base, type):
        base = base[kind]
    name = '{}_{}'.format(kind, cls.__name__)
    bases = (cls, base)
    specialized = types.new_class(name, bases)
    specialized.__module__ = cls.__module__
    specialized._NAME = cls.__name__
    specialized._KIND = kind
    for attr, values in kwargs.items():
        value = values[kind]
        setattr(specialized, attr, value)
    return specialized 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:19,代码来源:util.py

示例7: _make_skeleton_class

# 需要导入模块: import types [as 别名]
# 或者: from types import new_class [as 别名]
def _make_skeleton_class(type_constructor, name, bases, type_kwargs,
                         class_tracker_id, extra):
    """Build dynamic class with an empty __dict__ to be filled once memoized

    If class_tracker_id is not None, try to lookup an existing class definition
    matching that id. If none is found, track a newly reconstructed class
    definition under that id so that other instances stemming from the same
    class id will also reuse this class definition.

    The "extra" variable is meant to be a dict (or None) that can be used for
    forward compatibility shall the need arise.
    """
    skeleton_class = types.new_class(
        name, bases, {'metaclass': type_constructor},
        lambda ns: ns.update(type_kwargs)
    )
    return _lookup_class_or_track(class_tracker_id, skeleton_class) 
开发者ID:ray-project,项目名称:ray,代码行数:19,代码来源:cloudpickle.py

示例8: add_test_case

# 需要导入模块: import types [as 别名]
# 或者: from types import new_class [as 别名]
def add_test_case(self, test_case, attr_name):
        """
        Add around hooks to context from given unittest.TestCase class. Only
        hooks such as setUp or tearDown will be called, no tests will be
        included.
        """

        def wrap_test_case(self, example):
            def test_test_slide(_):
                example()

            def exec_body(ns):
                ns.update({"test_test_slide": test_test_slide})

            # Build a child class of given TestCase, with a defined test that
            # will run TestSlide example.
            test_slide_test_case = types.new_class(
                "TestSlideTestCase", bases=(test_case,), exec_body=exec_body
            )

            # This suite will only contain TestSlide's example test.
            test_suite = unittest.TestLoader().loadTestsFromName(
                "test_test_slide", test_slide_test_case
            )
            setattr(self, attr_name, list(test_suite)[0])
            result = _TestSlideTestResult()
            test_suite(result=result)
            if not result.wasSuccessful():
                result.aggregated_exceptions.raise_correct_exception()

        self.around_functions.append(wrap_test_case) 
开发者ID:facebookincubator,项目名称:TestSlide,代码行数:33,代码来源:__init__.py

示例9: _gen_keyword_tokens

# 需要导入模块: import types [as 别名]
# 或者: from types import new_class [as 别名]
def _gen_keyword_tokens():
    # Define keyword tokens

    mod = sys.modules[__name__]

    def clsexec(ns):
        ns['__module__'] = __name__
        return ns

    for token, _ in keywords.edgeql_keywords.values():
        clsname = 'T_{}'.format(token)
        clskwds = dict(metaclass=parsing.TokenMeta, token=token)
        cls = types.new_class(clsname, (Token,), clskwds, clsexec)
        setattr(mod, clsname, cls) 
开发者ID:edgedb,项目名称:edgedb,代码行数:16,代码来源:tokens.py

示例10: test_new_class_basics

# 需要导入模块: import types [as 别名]
# 或者: from types import new_class [as 别名]
def test_new_class_basics(self):
        C = types.new_class("C")
        self.assertEqual(C.__name__, "C")
        self.assertEqual(C.__bases__, (object,)) 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:6,代码来源:test_types.py

示例11: test_new_class_subclass

# 需要导入模块: import types [as 别名]
# 或者: from types import new_class [as 别名]
def test_new_class_subclass(self):
        C = types.new_class("C", (int,))
        self.assertTrue(issubclass(C, int)) 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:5,代码来源:test_types.py

示例12: test_new_class_meta

# 需要导入模块: import types [as 别名]
# 或者: from types import new_class [as 别名]
def test_new_class_meta(self):
        Meta = self.Meta
        settings = {"metaclass": Meta, "z": 2}
        # We do this twice to make sure the passed in dict isn't mutated
        for i in range(2):
            C = types.new_class("C" + str(i), (), settings)
            self.assertIsInstance(C, Meta)
            self.assertEqual(C.y, 1)
            self.assertEqual(C.z, 2) 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:11,代码来源:test_types.py

示例13: test_new_class_exec_body

# 需要导入模块: import types [as 别名]
# 或者: from types import new_class [as 别名]
def test_new_class_exec_body(self):
        Meta = self.Meta
        def func(ns):
            ns["x"] = 0
        C = types.new_class("C", (), {"metaclass": Meta, "z": 2}, func)
        self.assertIsInstance(C, Meta)
        self.assertEqual(C.x, 0)
        self.assertEqual(C.y, 1)
        self.assertEqual(C.z, 2) 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:11,代码来源:test_types.py

示例14: test_new_class_metaclass_keywords

# 需要导入模块: import types [as 别名]
# 或者: from types import new_class [as 别名]
def test_new_class_metaclass_keywords(self):
        #Test that keywords are passed to the metaclass:
        def meta_func(name, bases, ns, **kw):
            return name, bases, ns, kw
        res = types.new_class("X",
                              (int, object),
                              dict(metaclass=meta_func, x=0))
        self.assertEqual(res, ("X", (int, object), {}, {"x": 0})) 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:10,代码来源:test_types.py

示例15: test_new_class_meta_with_base

# 需要导入模块: import types [as 别名]
# 或者: from types import new_class [as 别名]
def test_new_class_meta_with_base(self):
        Meta = self.Meta
        def func(ns):
            ns["x"] = 0
        C = types.new_class(name="C",
                            bases=(int,),
                            kwds=dict(metaclass=Meta, z=2),
                            exec_body=func)
        self.assertTrue(issubclass(C, int))
        self.assertIsInstance(C, Meta)
        self.assertEqual(C.x, 0)
        self.assertEqual(C.y, 1)
        self.assertEqual(C.z, 2)

    # Many of the following tests are derived from test_descr.py 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:17,代码来源:test_types.py


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