python常见的魔法函数(函数名前后带双下横线)备注

1.__init__

初始化对象实例:

#!/usr/bin/python3

class People:
  def __init__(self,name=''):
    self.name = name

a = People("zhangsan")
print(a.name)
  

2.__getitem__

通过中括号访问类的实例中的元素:

#!/usr/bin/python3

class People:
  def __init__(self,name='',age=3):
    self.name = name
    self.age = age
  def __getitem__(self,key):
    if key == 'name':
      return self.name
    elif key == 'age':
      return self.age
    else:
      return None

a = People("zhangsan")
print(a['name'])
print(a['age'])

3.__setitem__

通过中括号设置类的实例中的元素:

#!/usr/bin/python3

class People:
  def __init__(self,name='',age=3):
    self.name = name
    self.age = age

  def __getitem__(self,key):
    if key == 'name':
      return self.name
    elif key == 'age':
      return self.age
    else:
      return None

  def __setitem__(self,key,value):
    if key == 'name':
      self.name = value
    elif key == 'age':
      self.age = value
    else:
      return

a = People("zhangsan")
print(a['name'])
print(a['age'])
a['name'] = 'lisi'
a['age'] = 4
print(a['name'])
print(a['age'])

4.__contains__

python中in方法的实现:

#!/usr/bin/python3

class People:
  def __init__(self,name='',age=3):
    self.name = name
    self.age = age
  def __getitem__(self,key):
    if key == 'name':
      return self.name
    elif key == 'age':
      return self.age
    else:
      return None
  def __contains__(self,key):
    if key == "name" or key == 'age':
      return True
    else:
      return False

a = People("zhangsan")
print('name' in a)
print('age' in a)
print('sex' in a)

5.__iter__和__next__

让对象可以用for … in obj循环遍历:

#!/usr/bin/python3

class People:
  def __init__(self,name='',age=0):
    self.name = name
    self.age = age
  
  def __iter__(self):
    self.item = 0
    return self
  
  def __next__(self):
    if self.item == 0:
      self.item = 1
      return self.name
    elif self.item == 1:
      self.item = 2
      return self.age
    else:
      raise StopIteration()
 
a = People("zhangsan")
for item in a:
  print(item)
print("循环已正常退出")

这里注意,__next__里面需要实现好退出机制,要不然会进入死循环,这里通过raise StopIteration异常可正常退出循环,使用exit(1)这种方式会导致程序退出,无法执行循环后面的语句。

6.__enter__和__exit__

配合with ... as ...使用,在with语句作用域内,自动在执行第一条语句前执行__enter__语句,自动在执行最后一条语句后执行__exit__函数,最常用的场景是with open('a.txt') as fp,其会在执行完with作用域语句后,自动执行fp.close()操作

#!/usr/bin/python3

class People:
  def __init__(self,name='',age=3):
    self.name = name
    self.age = age
  
  def __enter__(self):
    print("hello everyone!")
    return self
  
  def __exit__(self,exec_type,exec_value,exec_tb):
    print("good bye!")

with People("zhangsan") as zhangsan:
  print("my name is %s" % zhangsan.name)
  print("my age is %s" % zhangsan.age)

print("thanks zhangsan`s introduction")

7.__delitem__

支持del obj[item]的方式删除item元素:

#!/usr/bin/python3

class People:
  def __init__(self,name='',age=3):
    self.name = name
    self.age = age

  def __getitem__(self,key):
    if key == 'name':
      return self.name
    elif key == 'age':
      return self.age
    else:
      return None

  def __delitem__(self,key):
    if key == 'name':
      self.name = 'unknown'
    elif key == 'age':
      self.age = 0
    else:
      return

a = People("zhangsan")
print(a['name'])
print(a['age'])
del a['name']
print(a.name)
print(a.age)
del a['age']
print(a.name)
print(a.age)

8.__len__

返回实例长度

9.__repr__

实现实例的自我描述功能

#!/usr/bin/python3

class People:
  def __init__(self,name='',age=3):
    self.name = name
    self.age = age
  def __repr__(self):
    return "this is a people named %s age %s" % (self.name,self.age)

a = People("zhangsan")
print(a)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值