zoukankan      html  css  js  c++  java
  • ptyhon class定制方法

     

    __iter__

    如果一个类想被用于for ... in循环。须实现一个__iter__()方法,
    该方法返回一个迭代对象,然后,Python的for循环就会不断调用该迭代对象的__next__()方法拿到循环的下一个值,
    直到遇到StopIteration错误时退出循环。
    斐波那契数列为例
    class Fib(object):
    def __init__(self):
    self.a, self.b = 0, 1 # 初始化两个计数器a,b

    def __iter__(self):
    return self # 实例本身就是迭代对象,故返回自己

    def __next__(self):
    self.a, self.b = self.b, self.a + self.b # 计算下一个值
    if self.a > 100000: # 退出循环的条件
    raise StopIteration()
    return self.a # 返回下一个值
    把Fib实例作用于for循环:

    >>> for n in Fib():
    ... print(n)

    __getattr__()

    _getattr__是python里的一个内建函数
    当调用不存在的属性时,Python会试图调用__getattr__(self,'key')来获取属性,并且返回key
    def __getattr__(self, key):
    try:
    return self[key]
    except KeyError:
    raise AttributeError(r"'Dict' object has no attribute '%s'" % key)


    __call__

    任何类,只需要定义一个__call__()方法,就可以直接对实例进行调用
    class Student(object):
    def __init__(self, name):
    self.name = name

    def __call__(self):
    print('My name is %s.' % self.name)
    调用方式
    >>> s = Student('Michael')
    >>> s()   # self参数不要传入
    My name is Michael.

    朝闻道
  • 相关阅读:
    查看python关键字
    命令终端执行python
    Codeforces-462C. A Twisty Movement
    Codeforces-462A. A Compatible Pair
    Codeforces-446C. Pride
    Codeforces-Hello 2018C. Party Lemonade(贪心)
    Codeforces-33C. Wonderful Randomized Sum
    Codeforces-118D. Caesar's Legions(lazy dynamics)
    codeforces-73C. LionAge II
    Gym 101510C-Computer Science
  • 原文地址:https://www.cnblogs.com/wander-clouds/p/8460896.html
Copyright © 2011-2022 走看看