當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。