python 类中__int__和__str__的使用

class F:

def __str__(self):
return 'hello china'

def __int__(self):
return 123

res = F()
print(res) #结果是hello china
print(int(res))  #结果是123

创建的对象时,会自动去寻找类中的__str__函数,
当我们用int转换类创建的对象时,会自动去寻找类中的__int__函数

猜你喜欢

转载自www.cnblogs.com/jinbaobao/p/12049464.html