python面向对象编程高级篇之定制类__getitem__ __getattr__ __call__

__getitem__

该方法将对象生成可以索引的list,这样就可以直接通过下标索引了;例如

class Fib(object):
    def __getitem__(self, n):
        a, b = 1, 1
        for x in range(n):
            a, b = b, a + b
        return a
>>> f = Fib()
>>> f[0]
1
>>> f[1]
1
>>> f[2]
2
>>> f[3]
3
>>> f[10]
89
>>> f[100]
573147844013817084101

__getattr__

当调用不存在的属性时会自动调用该方法,可以显示提示等信息,没有提示的返回None

class Student(object):

    def __getattr__(self, attr):
        if attr=='age':
            return lambda: 25
        raise AttributeError('\'Student\' object has no attribute \'%s\'' % attr)

_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.

callable()用来检查对象是否可以调用,比如callable(Student())

参考来源:https://www.liaoxuefeng.com/wiki/1016959663602400/1017590712115904

猜你喜欢

转载自blog.csdn.net/li4692625/article/details/109502477