python学习日记(9)

  • 定制类
    • __str__
    • __iter__
    • __getattr__
    • __call__

定制类

__str__()

用以返回class的信息,还有__repr__()

__iter__()

用于循环

__getattr__()

设定未出现的属性

__call__

直接对实例进行调用

class foo():
    def __init__(self):
        self.a = 0
        self.b = 1
    def __str__(self):
        return("foo")
    def __iter__(self):
        return self
    def __next__(self):
        self.a, self.b = self.b, self.a + self.b
        if self.a > 10000:
            raise StopIteration()
        else:
            return self.a
    def __getitem__(self, sli):
        if isinstance(sli, int):
            a, b = 1, 1
            for x in range(n):
                a, b = b, a + b
            return a
        if isinstance(sli, slice):
            start = slice.start
            stop = slice.stop
            if start is None:
                start = 0
            a, b = 1, 1
            L = []
            for x in range(stop):
                if x >= start:
                    L.append(a)
                a, b = b, a + b
            return L
    def __getattr__(self, attr):
        if attr=='attr':
            return "fib"
        raise AttributeError('\'foo\' object has no attribute \'%s\'' % attr)

python学习日记(9)_第1张图片

你可能感兴趣的:(我的学习日记,python)