• 技术文章 >常见问题 >Python常见问题

    python中魔法怎么使用

    silencementsilencement2019-10-15 10:39:11原创2033

    简单的说,python中的魔法函数,就是以双下划线开头和双下划线结尾的函数,在类中定义后python解释器会执行。所以我们可以根据

    自己的场景需要使用不同的魔法函数。

    一个小实例假如我们想对类进行遍历取值,通常我们的做法可能如下

    class Company(object):
        def __init__(self, employee_list):
            self.employee = employee_list
     
    company = Company(["tom", "bob", "jane"])
     
     
    for item in company.employee:
        print(item)

    可以通过 __getitem__方法可以把一个类编程可迭代对象(序列类型)

    class Company(object):
        def __init__(self, employee_list):
            self.employee = employee_list
    
        def __getitem__(self, item):
            return self.employee[item]
    
    company = Company(["tom", "bob", "jane"])
    
    company1= company[:2]
    
    for item in company1:
        print(item)

    输出结果

    更多学习内容,请点击python学习网

    专题推荐:魔法方法
    上一篇:python中如何删除空格 下一篇:python怎么求除数

    相关文章推荐

    • python的魔法方法是什么• Python魔法方法之__getattr__和getattribute• Python黑魔法之property装饰器详解• python魔法方法是什么

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网