Python abc 模块,ABC 实例源码

我们从Python开源项目中,提取了以下11个代码示例,用于说明如何使用abc.ABC

项目:labgrid    作者:labgrid-project    | 项目源码 | 文件源码
def __getitem__(self, key):
        """
        Syntactic sugar to access drivers by class (optionally filtered by
        name).

        >>> target = Target('main')
        >>> console = FakeConsoleDriver(target, 'console')
        >>> target.activate(console)
        >>> target[FakeConsoleDriver]
        FakeConsoleDriver(target=Target(name='main', …), name='console', …)
        >>> target[FakeConsoleDriver, 'console']
        FakeConsoleDriver(target=Target(name='main', …), name='console', …)
        """
        name = None
        if not isinstance(key, tuple):
            cls = key
        elif len(key) == 2:
            cls, name = key
        if not issubclass(cls, (Driver, abc.ABC)): # all Protocols derive from ABC
            raise NoDriverFoundError(
                "invalid driver class {}".format(cls)
            )

        return self.get_active_driver(cls, name=name)
项目:pure_interface    作者:aranzgeo    | 项目源码 | 文件源码
def _type_is_pure_interface(cls):
    """ Return True if cls is a pure interface or an empty ABC class"""
    if cls is object:
        return False
    if hasattr(cls, '_pi'):
        return cls._pi.type_is_pure_interface
    if issubclass(type(cls), abc.ABCMeta):
        for attr, value in six.iteritems(cls.__dict__):
            if _builtin_attrs(attr):
                continue
            if callable(value):
                if not _is_empty_function(value):
                    return False
            elif isinstance(value, property):
                for func in (value.fget, value.fset, value.fdel):
                    if func is not None and not _is_empty_function(func):
                        return False
        return True

    return False
项目:pyabc    作者:neuralyzer    | 项目源码 | 文件源码
def __call__(self, t: int, history: History):
        """

        Parameters
        ----------
        t: int
            The population number. Counting is zero based. So the first
            population has t=0.

        history: History
            ABC history object. Can be used to query summary statistics to
            set the epsilon

        Returns
        -------

        eps: float
            The new epsilon for population ``t``.
        """
项目:attributeBasedClustering    作者:silenteddie    | 项目源码 | 文件源码
def classFactory(iface):
    from abc import ABC
    return ABC(iface)
项目:nelpy    作者:nelpy    | 项目源码 | 文件源码
def _rebin_array(arr, w):
        """Rebin an array of shape (n_signals, n_bins) into a
        coarser bin size.

        Parameters
        ----------
        arr : array
            Array with shape (n_signals, n_bins) to re-bin. A copy
            is returned.
        w : int
            Number of original bins to combine into each new bin.ABC

        Returns
        -------
        out : array
            Bnned array with shape (n_signals, n_new_bins)
        bin_idx : array
            Array of shape (n_new_bins,) with the indices of the new
            binned array, relative to the original array.
        """
        cs = np.cumsum(arr, axis=1)
        binidx = np.arange(start=w, stop=cs.shape[1]+1, step=w) - 1

        rebinned = np.hstack((np.array(cs[:,w-1], ndmin=2).T, cs[:,binidx[1:]] - cs[:,binidx[:-1]]))
        # bins = bins[np.insert(binidx+1, 0, 0)]
        return rebinned, binidx
项目:dengraph    作者:MaineKuehn    | 项目源码 | 文件源码
def register(cls, subclass):
                """
                Register *subclass* as a "virtual subclass" of this ABC.

                .. versionchanged:: 3.3
                   Returns the registered subclass, to allow usage as a class decorator.
                """
                cls.__metaclass__.register(cls, subclass)
                return cls
项目:dengraph    作者:MaineKuehn    | 项目源码 | 文件源码
def register(cls, subclass):
            """
            Register *subclass* as a "virtual subclass" of this ABC.

            .. versionchanged:: 3.3
               Returns the registered subclass, to allow usage as a class decorator.
            """
            cls.__class__.register(cls, subclass)
            return cls
项目:labgrid    作者:labgrid-project    | 项目源码 | 文件源码
def test_getitem(target):
    class AProtocol(abc.ABC):
        pass

    class A(Driver, AProtocol):
        pass

    class B(Driver):
        pass

    a = A(target, "adriver")
    target.activate(a)
    assert isinstance(target[A], A)
    assert target[A] is a
    assert target[AProtocol] is a
    assert target[A, "adriver"] is a
    assert target[AProtocol, "adriver"] is a
    with pytest.raises(NoDriverFoundError) as excinfo:
        target[A, "bdriver"]
    assert "have other names" in excinfo.value.msg
    with pytest.raises(NoDriverFoundError) as excinfo:
        target[B, "adriver"]
    assert "no active driver" in excinfo.value.msg

    a2 = A(target, None)
    target.activate(a2)
    with pytest.raises(NoDriverFoundError) as excinfo:
        target[A]
    assert "multiple active drivers" in excinfo.value.msg
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test_ABC_helper(self):
        # create an ABC using the helper class and perform basic checks
        class C(abc.ABC):
            @classmethod
            @abc.abstractmethod
            def foo(cls): return cls.__name__
        self.assertEqual(type(C), abc.ABCMeta)
        self.assertRaises(TypeError, C)
        class D(C):
            @classmethod
            def foo(cls): return super().foo()
        self.assertEqual(D.foo(), 'D')
项目:pure_interface    作者:aranzgeo    | 项目源码 | 文件源码
def _builtin_attrs(name):
    """ These attributes are ignored when checking ABC types for emptyness.
    """
    return name in ('__doc__', '__module__', '__qualname__', '__abstractmethods__', '__dict__',
                    '__metaclass__', '__weakref__',
                    '_abc_cache', '_abc_registry', '_abc_negative_cache_version', '_abc_negative_cache')
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
def test_ABC_helper(self):
        # create an ABC using the helper class and perform basic checks
        class C(abc.ABC):
            @classmethod
            @abc.abstractmethod
            def foo(cls): return cls.__name__
        self.assertEqual(type(C), abc.ABCMeta)
        self.assertRaises(TypeError, C)
        class D(C):
            @classmethod
            def foo(cls): return super().foo()
        self.assertEqual(D.foo(), 'D')