Python类的一些有趣的函数

我们在使用Python时,常会用到一些方法,如print,len,对象比较等,举一个例子:
>>> l = range(10)
>>> print l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> len(l)
10
>>> l1 = range(1)
>>> l > l1
True
>>> 


如果自己实现一个类,是否可以使用这些方法呢,我们来简单试一下:

>>> t = Test(10)
>>> t2 = Test(1)
>>> print t
<__main__.Test instance at 0x01C884B8>
>>> t
<__main__.Test instance at 0x01C884B8>
>>> len(t)

Traceback (most recent call last):
  File "<pyshell#72>", line 1, in <module>
    len(t)
AttributeError: Test instance has no attribute '__len__'
>>> t > t2
True
>>> 

从上面的例子可以看到,print打印出来的内容与list打印是有区别的,另外len调用报错,说Test中没有__len__,并且对于t>t2的比较,也不是按照value的值来比较的,当然前面的list比较也存在这个问题,那对于构造类,我们就无能为力了吗。其实不是这样的,在Python里我们是可以对这些行为进行定义的

当我们在python里调用print t时,实际上是调用了print str(t),而str(t)内部,则调用了t的__str__(self)方法,我们只要对这个方法进行重定义即可控制print t的输出:

>>> class Test:
	def __init__(self, v):
		self.value = v
	def __str__(self):
		return "This is a Test class"

>>> t = Test(100)
>>> print t
This is a Test class
>>> t
<__main__.Test instance at 0x01D14C88>
>>> 
上面,我们重定义了Test的__str__方法,可以看到print t变为了:

This is a Test class

但是我们直接输出t,其结果仍然为:

<__main__.Test instance at 0x01D14C88>
那是因为这个输出调用的是__repr__,而类似的,len调用的是__len__,对象比较调用了__cmp__,我们可以按照这个思路对Test进行补充:

>>> class Test:
	def __init__(self, v):
		self.value = v
	def __str__(self):
		return "__str__: Test class"
	def __repr__(self):
		return "__repr__: Test class"
	def __len__(self):
		return 8
	def __cmp__(self, t):
		if self.value < t.value:
			return -1
		elif self.value > t.value:
			return 1
		else:
			return 0

		
>>> t = Test(10)
>>> t2 = Test(1)
>>> print t
__str__: Test class
>>> t
__repr__: Test class
>>> len(t)
8
>>> t > t2
True
>>> t3 = Test(88)
>>> t > t3
False

Python里还有许多类似的方法,如:

__getitem__(self, key)

__setitem__(self, key, value)

__delitem__(slef, key)

__getattribute__(self, name)

__getattr__(self, name)

__setattr__(self, name)

__iter__(self)

这些函数主要和列表,字典等类型相关,使用dir(list)或dir(dict)都可以看到

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值