|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- class Nstr:
- def __init__(self, arg=' '):
- self = ord(arg)
- print(self)#检测
- print(type(self))#检测
- def __add__(self, other):
- print(self)#检测
- print(type(self))#检测
- return int.__add__(self) + int(other)
复制代码
输出结果
- >>> b = Nstr('b'); a = Nstr('a'); a + b
- 98
- <class 'int'>
- 97
- <class 'int'>
- <__main__.Nstr object at 0x000001EAA1625C88>
- <class '__main__.Nstr'>
- Traceback (most recent call last):
- File "<pyshell#31>", line 1, in <module>
- b = Nstr('b'); a = Nstr('a'); a + b
- File "C:\Users\Jason\Desktop\test03.py", line 10, in __add__
- return int.__add__(self) + int(other)
- TypeError: descriptor '__add__' requires a 'int' object but received a 'Nstr'
复制代码
请问一下啊
self不是全局变量吗,我修改了self的类型后为什么后来它的类型又变回去了?
Java:
class Demo{
int value;
public Demo(int value){
this.value = value; // 虽然在Java的方法签名中没有显式写出this,但是JVM把实例对象this传进去
}
}
Python:
class Demo(object):
def __init__(self, value):
self.value = value # Python就比较直接,在初始化方法的参数中传进self参数,用来标记该类的实例对象
|
|