Python之路,第十九篇:Python入门与基础19

python3  面向对象3

数值转换函数重载:

str(obj)              __str__

complex(x)       __complex__

int(obj)              __int__

float(obj)           __float__

bool                 __bool__

 1 class MyNumber:
 2     def __init__(self,n):
 3         self.data = n
 4 
 5     def __float__(self):
 6         print("__float__被调用。")
 7         try:
 8             x = float(self.data)
 9         except:
10             x = 0.0
11         return x
12 
13 
14 n = MyNumber('100')
15 print(float(n))  #__float__被调用。   #100.0
16 
17 print(float("100.0"))  #100.0
18 print(float(True))  #1.0
19 
20 n = MyNumber(1+2j)
21 print(float(n)) #__float__被调用。  #0.0
View Code

bool 测试运算符重载:

方法格式:def   __bool__(self):

                            .......

作用:1, 用于if 语句的真值表达式中:

           2, 用于while   语句的真值表达式中;

           3,用于bool(obj) 函数取值;

说明:当没有__bool__ (self)方法时, 真值测试将以__len__(self)的方法的返回值来进行测试布尔值;

猜你喜欢

转载自www.cnblogs.com/weizitianming/p/9107607.html
今日推荐