当前位置: 移动技术网 > IT编程>脚本编程>Python > Python中的特殊方法以及应用详解

Python中的特殊方法以及应用详解

2020年09月21日  | 移动技术网IT编程  | 我要评论
前言python 中的特殊方法主要是为了被解释器调用的,因此应该尽量使用 len(my_object) 而不是 my_object.__len__() 这种写法。在执行 len(my_object)

前言

python 中的特殊方法主要是为了被解释器调用的,因此应该尽量使用 len(my_object) 而不是 my_object.__len__() 这种写法。在执行 len(my_object) 时,python 解释器会自行调用 my_object 中实现的 __len__ 方法。

除非有大量的元编程存在,直接调用特殊方法的频率应远小于实现它们的次数。

模拟数值类型

可以通过在自定义对象中实现 __add__ 和 __mul__ 等特殊方法 ,令其支持 +、* 等运算符。

如下面的模拟向量的 vector 类:

# vector.py
from math import hypot

class vector:
  def __init__(self, x=0, y=0):
    self.x = x
    self.y = y

  def __repr__(self):
    return f'vector({self.x}, {self.y})'

  def __abs__(self):
    return hypot(self.x, self.y)

  def __bool__(self):
    return bool(self.x or self.y)

  def __add__(self, other):
    return vector(self.x + other.x, self.y + other.y)

  def __mul__(self, scalar):
    return vector(self.x * scalar, self.y * scalar)

运行效果如下:

>>> from vector import vector
>>> v1 = vector(2, 4)
>>> v2 = vector(2, 1)
>>> v1 + v2
vector(4, 5)
>>> v = vector(3, 4)
>>> abs(v)
5.0
>>> v * 3
vector(9, 12)

对象的字符串表示

python 有一个 repr 内置函数,能把一个对象用字符串的形式表示出来。实际上这种字符串表达是通过对象内部的 __repr__ 特殊方法定义的。默认情况下,在控制台里查看某个对象时,输出的字符串一般是 <xxx object at 0x7fc99d6ab2e0> 这种形式。

__repr__ 返回的字符串应该准确、无歧义,并尽可能表示出该对象是如何创建的。比如前面的 vector 对象,其 __repr__ 中定义的字符串形式类似于 vector(3, 4),和对象初始化的语法非常近似。

__repr__ 和 __str__ 的区别在于,__str__ 是在向对象应用 str() 函数(或者用 print 函数打印某个对象)时被调用。其返回的字符串对终端用户更友好。

如果只想实现其中一个特殊方法,__repr__ 应该是更优的选择。在对象没有实现 __str__ 方法的情况下,python 解释器会用 __repr__ 代替。

# myclass.py
class myclass:
  def __repr__(self):
    return 'myclass'

  def __str__(self):
    return 'this is an instance of myclass'

>>> from myclass import myclass
>>> my = myclass()
>>> my
myclass
>>> print(my)
this is an instance of myclass

自定义布尔值

python 里有 bool 类型,但实际上任何对象都可以用在需要 bool 类型的上下文(比如 if 或 while 语句)中。为了判断某个值 x 的真假,python 会调用 bool(x) 返回 true 或 false。

默认情况下,自定义类的实例总是为真。除非这个类对于 __bool__ 或 __len__ 方法有自己的实现。
bool(x) 实际上调用了对象 x 中的 __bool__ 方法。如不存在 __bool__ 方法,则 bool(x) 会尝试调用 x.__len__(),返回 0 则为 false,否则为 true。

# boolclass.py
class boolclass:
  def __init__(self):
    self.list = []

  def add(self, item):
    self.list.append(item)

  def __len__(self):
    return len(self.list)

>>> from boolclass import boolclass
>>> b = boolclass()
>>> len(b)
0
>>> bool(b)
false
>>> b.add(1)
>>> len(b)
1
>>> bool(b)
true
# boolclass.py
class boolclass:
  def __init__(self):
    self.list = []

  def add(self, item):
    self.list.append(item)

  def __len__(self):
    return len(self.list)

  def __bool__(self):
    return bool(sum(self.list))

>>> from boolclass import boolclass
>>> b = boolclass()
>>> b.add(1)
>>> len(b)
1
>>> bool(b)
true
>>> b.add(-1)
>>> len(b)
2
>>> bool(b)
false

参考资料

总结

到此这篇关于python中特殊方法以及应用详解的文章就介绍到这了,更多相关python特殊方法及应用内容请搜索移动技术网以前的文章或继续浏览下面的相关文章希望大家以后多多支持移动技术网!

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网