python 用于进一步子类化和构建的Python元类的基本示例。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 用于进一步子类化和构建的Python元类的基本示例。相关的知识,希望对你有一定的参考价值。

from abc import ABCMeta, abstractmethod           # need these definitions

class Sequence():
    """Our own version of collections.Sequence abstract base class."""
    
    __metaclass__ = ABCMeta

    @abstractmethod
    def __len__(self):
        """Return the length of the sequence."""
    
    @abstractmethod
    def __getitem__(self, j):
        """Return the element at index j of the sequence."""
    
    def __contains__(self, val):
        """Return True if val found in the sequence; False otherwise."""
        for j in range(len(self)):
            if self[j] == val:                          # found match
                return True
            return False
    
    def index(self, val):
        """Return leftmost index at which val is found (or raise ValueError)."""
        for j in range(len(self)):
            if self[j] == val:                          # leftmost match
                return j
        raise ValueError('value not in sequence')     # never found a match
    
    def count(self, val):
        """Return the number of elements equal to given value."""
        k = 0
        for j in range(len(self)):
            if self[j] == val:                          # found a match
                k += 1
        return k
__author__ = 'szaydel'

from abc import ABCMeta, abstractmethod           # need these definitions

class Sequence():
    """Our own version of collections.Sequence abstract base class."""

    __metaclass__ = ABCMeta

    @abstractmethod
    def __len__(self):
        """Return the length of the sequence."""

    @abstractmethod
    def __getitem__(self, j):
        """Return the element at index j of the sequence."""

    def __contains__(self, val):
        """Return True if val found in the sequence; False otherwise."""
        for j in range(len(self)):
            if self[j] == val:                          # found match
                return True
            return False

    def index(self, val):
        """Return leftmost index at which val is found (or raise ValueError)."""
        for j in range(len(self)):
            if self[j] == val:                          # leftmost match
                return j
        raise ValueError('value not in sequence')     # never found a match

    def count(self, val):
        """Return the number of elements equal to given value."""
        k = 0
        for j in range(len(self)):
            if self[j] == val:                          # found a match
                k += 1
        return k


class SequenceIterator(object):
  """An iterator for any of Python's sequence types."""

  def __init__(self, sequence):
    """Create an iterator for the given sequence."""
    self._seq = sequence          # keep a reference to the underlying data
    self._k = -1                  # will increment to 0 on first call to next

  def __next__(self):
    """Return the next element, or else raise StopIteration error."""
    self._k += 1                  # advance to next index
    if self._k < len(self._seq):
      return(self._seq[self._k])  # return the data element
    else:
      raise StopIteration()       # there are no more elements

  def __iter__(self):
    """By convention, an iterator must return itself as an iterator."""
    return self


class MySeq(Sequence):
    """ This is a class created from our factory class.
    """
    def __init__(self, li):
        self.li = li
        
    def __len__(self):
        return len(self.li)
    
    def __getitem__(self, item):
        return self.li[item]


if __name__ == "__main__":
    seq = MySeq(["a", "b", "c", "d"])

    for i in seq:
        print i

以上是关于python 用于进一步子类化和构建的Python元类的基本示例。的主要内容,如果未能解决你的问题,请参考以下文章

python 在pytest fixture中即时构建子类

Python IsInstance() 用于类和子类

UITableViewHeaderFooterView 的正确子类化和自动布局

正确子类化和重用 UITableViewHeaderFooterView

子类化和覆盖使用 nib 文件创建的 UIView

使用 NSLayoutConstraint 实例化和设置 UIButton 子类的大小