python中的魔法函数

python中一切皆对象
魔法函数是在类中以双下划线开头,双下划线结尾的,python本身给我们定义了许多这种方法,让我们能在类中直接使用。

比如我们要遍历一个类中的列表,我们普通的做法如下

class Company(object):
    def __init__(self, employee_list):
        self.employee = employee_list

company = Company(['tom', 'bob', 'jane'])
employee = company.employee

for em in employee :
    print(em)

但如果我们使用魔法函数,就变成了

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'])


for em in company:
    print(em)

实例化一个类之后就可以直接遍历

用魔法函数,让列表输出时变成字符串,__str__这个函数会在被打印时自动调用

class Company(object):
    def __init__(self, employee_list):
        self.employee = employee_list

    def __str__(self):
        return ','.join(self.employee)


company = Company(['tom', 'bob', 'jane'])
print(company)

__add__的用法,在使用+的使用自动调用该方法

class MyVector(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def __add__(self, other_instance):
        re_vector = MyVector(self.x + other_instance.x, self.y + other_instance.y)
        return re_vector
    def __str__(self):
        return "x:{x},y:{y}".format(x=self.x, y=self.y)

first_vec = MyVector(1, 2)
second_vec = MyVector(2, 3)
print(first_vec + second_vec)

当我们使用len函数时,其实会调用魔法函数__len__,而且我们在遍历set,list,dict这些python内置的数据结构,它不会每次都去遍历,这样效率低,它会去维护一个数来保存他们的数量,因为这些内置的数据类型是用cpython解释器写的,底层是c语言,效率很高。

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值