02. 魔法函数

Python魔法函数

Python类置的函数,其函数形式__函数名__,魔法函数不需要去调用,Python解释器会内部调用

学习代码

# 魔法函数

class Company:
    """Python类置函数形式,__函数名__, 即为魔法函数
    1. 魔法函数不需要我们去调用,内部会自己调用
    """

    def __init__(self, employee_list):
        self.employee = employee_list

    def __getitem__(self, item):
        """定义了该函数,将表示该对象可迭代"""
        return self.employee[item]

    def __len__(self):
        """当对类使用len(class)时,将首先查找这个魔法函数,如果找不到就会再去找 __getitem__
        的长度 只对 切片后的实例长度显示
        """
        return len(self.employee)

    def __repr__(self):
        """交互时开发模式用到, 定义输入类后显示的内容"""
        return "<__repr__>".join(str(self.employee))

    def __str__(self):
        """非交互式开发模式用到,目的定义print后返回的内容"""
        return "<__str__>".join(str(self.employee))     # [<__str__>1<__str__>,<__str__> <__str__>2<__str__>,<__str__> <__str__>3<__str__>]


if __name__ == '__main__':
    company = Company([1, 2, 3])
    company1 = company[1:2]
    """注释了__len__, 如果不注释__len__都能正常运行 3, 1"""
    print(len(company))  # TypeError: object of type 'Company' has no len()

    # len()将去调用类中的__len__函数
    print(len(company1))  # 1

    # __str__没定义时将找__repr__,没找到时就 输出 <__main__.Company object at 0x0000023897E86460>
    print(company)
    #
    # # TypeError: 'Company' object is not iterable 注释了__getitem__将表示该对象无法迭代
    # for i in company:
    #     print(i)

原文地址:https://www.cnblogs.com/zy7y/p/14191932.html