python复习41~42魔方方法

魔方方法:

构造与析构:

一:构造器

__new__(cls[,...])

当继承一个不可变类型,有需要修改时,可以用此方法进行重写
主要作用是在一个对象实例化时返回一个实例对象,通常是参数cls这个类的实例化对象,到如也可以返回其它对象。

>>> class Capstr(str):
	def __new__(cls,string):
		string = string.upper()
		return str.__new__(cls,string)

	
>>> a=Capstr('I love carrot')
>>> a
'I LOVE CARROT'

二:析构器

__del__(self)

当对象要被销毁时,此方法会被调用,且当所有对生成对象的引用都被del之后,才会启用这个垃圾回收机制。

>>> class A:
	def __init__(self):
		print('我是__init_方法,我被调用了')
	def __del__(self):
		print('我是__del_方法,我被调用了')

		
>>> a1=A()
我是__init_方法,我被调用了
>>> a2=a1
>>> a3=a2
>>> del a2
>>> del a1
>>> del a3
我是__del_方法,我被调用了

当实例对象需要有明确的初始化步骤时,可以用下面的方法

__init__(self)
class Rectangle: 
	def __init__(self, x, y): 
		self.x = x 
		self.y = y
	def getPeri(self): 
		return (self.x + self.y) * 2 
	def getArea(self): 
		return self.x * self.y 
rect = Rectangle(3, 4)  
rect.getPeri()
输出 
14  
rect.getArea() 
输出
12 

注意_ _ init_ _()方法返回值一定是None不能是其它

>>> class Test:
	def __init__(self,x,y):
		return x+y

	
>>> t=Test(3,4)
Traceback (most recent call last):
  File "<pyshell#65>", line 1, in <module>
    t=Test(3,4)
TypeError: __init__() should return None, not 'int'

算数运算:

对象是可以进行计算的

>>> a=int('123')
>>> b=int('456')
>>> c=float('345')
>>> a+b
579
>>> a+c
468.0

python的魔方方法还可以自定义进行对象的数值处理

方法作用
add(self,other)定义加法的行为
sub(self,other)定义减法的行为
mul(self,other)定义乘法的行为
truediv(self,other)定义真除法的行为
floordiv(self,other)定义整数除法的行为
mod(self,other)定义取模算法的行为
divmod(self,other)定义当divmod()调用时的行为(a\\b余数)
pow(self,other)定义当被power()调用或**运算时的行为
lshift(self,other)定义按位左移位的行为
rshift(self,other)定义按位右移位的行为
and(other)定义安按位与操作的行为&
xor(self,other)定义按位异或操作的行为:^
or(self,other)定义按位或操作的行为
>>> class New_int(int):
	def __add__(self,other):
		return int.__sub__(self,other)
	def __sub__(self,other):
		return int.__add__(self,other)

	
>>> a=New_int(3)
>>> b=New_int(5)
>>> a+b
-2
>>> a-b
8
#+返回-,-返回+

这里进入了无限递归的死循环,因为self绑定的是a,当执行a+b时,return self+other 则又是a+b,a+b一直循环。

>>> class Try_int(int):
	def __add__(self,other):
		return self+other
	def __sub__(self,other):
		return self-other

	
>>> a=Try_int(3)
>>> b=Try_int(5)
>>> a+b
Traceback (most recent call last):
  File "<pyshell#53>", line 1, in <module>
    a+b
  File "<pyshell#49>", line 3, in __add__
    return self+other
  File "<pyshell#49>", line 3, in __add__
    return self+other
  File "<pyshell#49>", line 3, in __add__
    return self+other
  [Previous line repeated 1022 more times]
RecursionError: maximum recursion depth exceeded

可以这样改进:

>>> class Try_int(int):
	def __add__(self,other):
		return int(self)+int(other)
	def __sub__(self,other):
		return int(self)-int(other)

	
>>> a=Try_int(3)
>>> b=Try_int(5)
>>> a+b
8
>>> a-b
-2

练习题:

1:给文件对象进行包装,使在删除对象时文件能自动关闭

>>> class Fileclose:
	def __init__(self,filename='D:\\carrot1.txt'):
		self.file=open(filename,'r',encoding='utf-8')
	def __del__(self):
		self.file.close()
		del self.file

2:定义一个类实现摄氏度到华氏度的转换(华氏度=摄氏度*1.8+32)

>>> class Cs(float):
	'摄氏度转换为华氏度'
	def __new__(cls,arg):
		return float.__new__(cls,arg*1.8+32)
>>> cs=Cs(9)
>>> cs
48.2		

3:定义一个类继承于int类型,并实现:当传入的参数是字符串的时候,返回改字符串的所有字符的ASCII码的和(使用ord()获取一个字符的ASCII码值)。

>>> class A(int):
	def __new__(cls,arg):
		if isinstance(arg,str):
			total=0
			for each in arg:
				total+=ord(each)
			arg=total
		return int.__new__(cls,arg)

	
>>> a=A('CARROT')
>>> a
459

4.两个字符串相加会自动拼接字符串,相减会抛出异常,选择定义一个类,使A-B时,从A中取出所有有B的子字符串。

>>> class A(str):
	def __sub__(self,other):
		return self.replace(other,'')

	
>>> a=A('I love carrothhhhhhf')
>>> b=A('hf')
>>> a-b
'I love carrothhhhh'
>>> c=A('h')
>>> a-c
'I love carrotf'
#a,b,c的值未变

5.定义一个类,当该类的实例对象间发生的加、减、乘、除运算时,将该对象的所有字符串的ASCII码之和进行运算。

class A:
    def __init__(self,arg):
        if isinstance(arg,str):
            self.total=0
            for each in arg:
                self.total+=ord(each)

        else:
            print('参数输入错误')

    def __add__(self,other):
        return self.total+other.total
    def __sub__(self,other):
        return self.total-other.total
    def __mul__(self,other):
        return self.total*other.total
    def __truediv__(self,other):
        return self.total/other.total
    def __floordiv__(self,other):
        return self.total//other.total
>>> print(a1+a2)
945
>>> print(a1*a2)
191394
>>> print(a1-a2)
-357
>>> print(a1/a2)
0.45161290322580644
>>> print(a1//a2)
0

6.运用移位操作符

>>> class A(str):
	def __lshift__(self,other):
		return self[other:]+self[:other]
	def __rshift__(self,other):
		return self[-other:]+self[:-other]

	
>>> a=A('I love carrot')
>>> a<<3
'ove carrotI l'
>>> a>>3
'rotI love car'
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值