Python object-oriented programming advanced articles custom class __getitem__ __getattr__ __call__

__getitem__

This method generates an indexable list of objects, so that they can be directly indexed by subscripts; for example

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__

This method is automatically called when a non-existent property is called, which can display prompts and other information, and returns None if there is no prompt

class Student(object):

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

_call__

Certain methods can be called directly through the instance; for example

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() is used to check whether the object can be called, such as callable(Student())

 

Reference source: https://www.liaoxuefeng.com/wiki/1016959663602400/1017590712115904

Guess you like

Origin blog.csdn.net/li4692625/article/details/109502477