• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python types.new_class函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: _copy_module

def _copy_module(module, include=None, exclude=None):
    copied = types.ModuleType(module.__name__)
    copied.__package__ = getattr(module, "__package__", None)
    for name, value in module.__dict__.items():
        if (name.startswith("_") or (exclude is not None and name in exclude) or
                (include is not None and name not in include)):
            continue
        type_ = type(value)
        if value is None or type_ in (bool, bytes, float, int, str):
            setattr(copied, name, value)
        elif type_ in (types.FunctionType, types.LambdaType,
                       types.BuiltinFunctionType):
            def func_proxy(func):
                """Return a proxy for the given function."""
                # pylint: disable=unnecessary-lambda
                return lambda *args, **kwargs: func(*args, **kwargs)
            setattr(copied, name, func_proxy(value))
        elif type_ is type and value is not type:
            try:
                proxy = types.new_class(name, bases=(value,))
                proxy.mro = lambda: []
                setattr(copied, name, types.new_class(name, bases=(proxy,)))
            except TypeError:
                pass
    return copied
开发者ID:jribbens,项目名称:unsafe,代码行数:25,代码来源:unsafe.py


示例2: test_errors

    def test_errors(self):
        class MyMeta(type):
            pass

        with self.assertRaises(TypeError):
            class MyClass(metaclass=MyMeta, otherarg=1):
                pass

        with self.assertRaises(TypeError):
            types.new_class("MyClass", (object,),
                            dict(metaclass=MyMeta, otherarg=1))
        types.prepare_class("MyClass", (object,),
                            dict(metaclass=MyMeta, otherarg=1))

        class MyMeta(type):
            def __init__(self, name, bases, namespace, otherarg):
                super().__init__(name, bases, namespace)

        with self.assertRaises(TypeError):
            class MyClass(metaclass=MyMeta, otherarg=1):
                pass

        class MyMeta(type):
            def __new__(cls, name, bases, namespace, otherarg):
                return super().__new__(cls, name, bases, namespace)

            def __init__(self, name, bases, namespace, otherarg):
                super().__init__(name, bases, namespace)
                self.otherarg = otherarg

        class MyClass(metaclass=MyMeta, otherarg=1):
            pass

        self.assertEqual(MyClass.otherarg, 1)
开发者ID:abalkin,项目名称:cpython,代码行数:34,代码来源:test_subclassinit.py


示例3: test_both

def test_both(test_class, **kwargs):
    frozen_tests = types.new_class('Frozen_'+test_class.__name__,
                                   (test_class, unittest.TestCase))
    source_tests = types.new_class('Source_'+test_class.__name__,
                                   (test_class, unittest.TestCase))
    frozen_tests.__module__ = source_tests.__module__ = test_class.__module__
    for attr, (frozen_value, source_value) in kwargs.items():
        setattr(frozen_tests, attr, frozen_value)
        setattr(source_tests, attr, source_value)
    return frozen_tests, source_tests
开发者ID:0jpq0,项目名称:kbengine,代码行数:10,代码来源:util.py


示例4: extension_add_event

    def extension_add_event(self, code, evt, name = None):
        """extension_add_event(code, evt, [name])

        Add an extension event.  CODE is the numeric code, and EVT is
        the event class.  EVT will be cloned, and the attribute _code
        of the new event class will be set to CODE.

        If NAME is omitted, it will be set to the name of EVT.  This
        name is used to insert an entry in the DictWrapper
        extension_event.
        """

        if hasattr(types, 'ClassType'):
            newevt = types.ClassType(evt.__name__, evt.__bases__,
                                     evt.__dict__.copy())
        else:
            newevt = types.new_class(evt.__name__, evt.__bases__,
                                     evt.__dict__.copy())
        newevt._code = code

        self.display.add_extension_event(code, newevt)

        if name is None:
            name = evt.__name__

        setattr(self.extension_event, name, code)
开发者ID:Sebelino,项目名称:python-xlib,代码行数:26,代码来源:display.py


示例5: extension_add_subevent

    def extension_add_subevent(self, code, subcode, evt, name = None):
        """extension_add_subevent(code, evt, [name])

        Add an extension subevent.  CODE is the numeric code, subcode
        is the sub-ID of this event that shares the code ID with other
        sub-events and EVT is the event class.  EVT will be cloned, and
        the attribute _code of the new event class will be set to CODE.

        If NAME is omitted, it will be set to the name of EVT.  This
        name is used to insert an entry in the DictWrapper
        extension_event.
        """

        if hasattr(types, 'ClassType'):
            newevt = types.ClassType(evt.__name__, evt.__bases__,
                                     evt.__dict__.copy())
        else:
            newevt = types.new_class(evt.__name__, evt.__bases__,
                                     evt.__dict__.copy())
        newevt._code = code

        self.display.add_extension_event(code, newevt, subcode)

        if name is None:
            name = evt.__name__

        # store subcodes as a tuple of (event code, subcode) in the
        # extension dict maintained in the display object
        setattr(self.extension_event, name, (code,subcode))
开发者ID:Sebelino,项目名称:python-xlib,代码行数:29,代码来源:display.py


示例6: data_entry_form

    def data_entry_form(self, row_name='new', data_instance = None, depth = 2):
        self.form_class = None
        self.classattr = {}

        if data_instance is None:
            data_instance = DataInstance(self.table_name, row_name, depth)

            if row_name != 'new':
                data_instance.get_linked_instances()

        self.instance = data_instance

        self.get_table(data_instance)

        self.classattr['form_data_type_0'] = HiddenField('form_data_type_0', default=self.form_type)
        self.classattr['form_data_table_0'] = HiddenField('form_data_table_0', default=self.table_name)
        self.classattr['form_data_row_name_0'] = HiddenField('form_data_row_name_0', default=row_name)
        self.classattr['row_counter'] = HiddenField('row_counter', default=data_instance.instance_counter)

        form_class = new_class('SingleForm', (Form,), {}, lambda ns: ns.update(self.classattr))

        logging.info(self.classattr)
        logging.info(self.classattr)

        self.form_class = form_class(None)
开发者ID:harvardinformatics,项目名称:iggybase,代码行数:25,代码来源:form_generator.py


示例7: make_abc_subclasses

def make_abc_subclasses(base_class):
    classes = []
    for kind, abc in [('Frozen', frozen_abc), ('Source', source_abc)]:
        name = '_'.join([kind, base_class.__name__])
        base_classes = base_class, getattr(abc, base_class.__name__)
        classes.append(types.new_class(name, base_classes))
    return classes
开发者ID:0jpq0,项目名称:kbengine,代码行数:7,代码来源:test_abc.py


示例8: test_metaclass_override_function

    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:abusalimov,项目名称:cpython,代码行数:16,代码来源:test_types.py


示例9: ensure_tomes

 def ensure_tomes(self):
     for number in range(1, 29):
         class_id = 'Tome_{0:02d}'.format(number)
         self.tomes[number] = types.new_class(
             correct_owl_id(class_id),
             (Tome, ),
             kwds = { "ontology" : onto }
         )
开发者ID:pitcons,项目名称:bme-parser,代码行数:8,代码来源:bme3import.py


示例10: test_new_class_metaclass_keywords

 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:abusalimov,项目名称:cpython,代码行数:8,代码来源:test_types.py


示例11: test_new_class_meta

 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:abusalimov,项目名称:cpython,代码行数:9,代码来源:test_types.py


示例12: decorator

    def decorator(cls):
        assert isinstance(driver, Driver)
        assert issubclass(cls, Schema)
        assert not issubclass(cls, DrivedMixin)

        drived_class = new_class(cls.__name__, (cls, DrivedMixin))
        drived_class.driver = driver

        return drived_class
开发者ID:NoZip,项目名称:uzu,代码行数:9,代码来源:schema.py


示例13: test_new_class_exec_body

 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:abusalimov,项目名称:cpython,代码行数:9,代码来源:test_types.py


示例14: test_prepare_class

    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:abusalimov,项目名称:cpython,代码行数:18,代码来源:test_types.py


示例15: make_return_value_tests

def make_return_value_tests(base_class, test_class):
    frozen_class, source_class = make_abc_subclasses(base_class)
    tests = []
    for prefix, class_in_test in [('Frozen', frozen_class), ('Source', source_class)]:
        def set_ns(ns):
            ns['ins'] = class_in_test()
        tests.append(types.new_class('_'.join([prefix, test_class.__name__]),
                                     (test_class, unittest.TestCase),
                                     exec_body=set_ns))
    return tests
开发者ID:0jpq0,项目名称:kbengine,代码行数:10,代码来源:test_abc.py


示例16: subclass

 def subclass(cls, name, bases, dict={}):
     if not isinstance(bases, tuple):
         bases = (bases,)
     name = name.encode('utf-8')
     key = '.'.join((name, str(bases)))
     subclass = cls.cache.get(key)
     if subclass is None:
         subclass = types.new_class(name, bases, dict)
         #subclass = classobj(name, bases, dict)
         cls.cache[key] = subclass
     return subclass
开发者ID:yuetianle,项目名称:suds-python3.5,代码行数:11,代码来源:sudsobject.py


示例17: test_tests_fail_1

    def test_tests_fail_1(self):
        SimpleTestCase = types.new_class('SimpleTestCase',
                                         (BaseSimpleTestCase, tb.TestCase))

        suite = unittest.TestSuite()
        suite.addTest(SimpleTestCase('test_tests_zero_error'))

        result = unittest.TestResult()
        suite.run(result)

        self.assertIn('ZeroDivisionError', result.errors[0][1])
开发者ID:Libardo1,项目名称:asyncpg,代码行数:11,代码来源:test_test.py


示例18: Event

def Event(name):
    """
    A mutator for events.

    Still unproven if it works, but *should*
    dynamically make classes for each unique event.
    This way, debugging is easier,
    since we can tell which event is which.
    """
    c = new_class(name, bases=(_Event,))(name)
    return c
开发者ID:hobosteaux,项目名称:bytelynx,代码行数:11,代码来源:event.py


示例19: parametrize

def parametrize(TestCase):
  '''Parametrize a :class:`unittest.TestCase`.

  >>> @parametrize
  ... class TestSomething(unittest.TestCase):
  ...   def test_equality(self):
  ...     self.assertEqual(self.x, self.y)
  >>> TestSomething(x=1, y=1)
  >>> TestSomething(x=2, y=2)
  '''
  return types.new_class(TestCase.__name__, (), dict(metaclass=_ParametrizedCollection, base=TestCase))
开发者ID:wijnandhoitinga,项目名称:nutils,代码行数:11,代码来源:__init__.py


示例20: _new_nonterm

def _new_nonterm(clsname, clsdict={}, clskwds={}, clsbases=(Nonterm,)):
    mod = sys.modules[__name__]

    def clsexec(ns):
        ns['__module__'] = __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:virajs,项目名称:edgedb,代码行数:12,代码来源:ddl.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python types.FunctionType类代码示例发布时间:2022-05-27
下一篇:
Python types.namespace函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap