|
发表于 2020-6-25 15:17:00
From FishC Mobile
|
显示全部楼层
|阅读模式
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- class Nstr(str):
- def __init__(self,arg=''):
- self.num=0
- for each in self:
- self.num+=ord(each)
-
- def __add__(self,other):
- return int.__add__(self.num,other.num)
- def __sub__(self,other):
- return int.__sub__(self.num,other.num)
- def __mol__(self,other):
- return self.num*other.num
- def __truediv__(self,other):
- return self.num/other.num
- def __floordiv__(self,other):
- return self.num//other.num
-
- a=Nstr('FishC')
- b=Nstr('love')
- c=a/b
- print(c
复制代码 ]
for each in self为什么也可以?和for each in arg的效果一毛一样
另外
- for each in self为什么也可以?和for each in arg的效果一毛一样
复制代码
这是因为 Nstr 是继承 str 的。
只要学了类的都知道 self 指代的是实例对象。
这里的 a 也是 类 str 的一个实例对象,在实例化的过程中,也就是调用 __init__ 和 __new__等的初始化过程中,a 和 self 是相同的,而 a 又等于 FishC,所以 self 也等于 FishC。
这里的 FishC 就是你传入的实参 argument,、而在 Nstr 是用parameter arg 来接收 argument 'FishC' 的,所以 self 和 arg 是等价的。
|
|