1+ __author__ = "Jerry"
2+ __version__ = "1.2.0"
3+
4+ class NotComposedOfNumbersError (Exception ):
5+ "不是由数字组成的字符串使用String对象的toInt()函数或toInteger()函数时抛出"
6+ pass
7+
8+ class String :
9+ "字符串类,是对Python原版字符串的加强"
10+ def __init__ (self , str_ ) -> None :
11+ if type (str_ ) is not str :
12+ raise TypeError (
13+ "请使用字符串类型来创建String对象"
14+ )
15+ self .__str = str_
16+ self .length = len (str_ ) # 字符串大小
17+
18+ def __repr__ (self ) -> str :
19+ return self .__str
20+
21+ __str__ = __repr__
22+
23+ def __add__ (self , other ):
24+ "当与一个字符串或另一个String对象进行加操作时调用"
25+ if type (other ) is String :
26+ return self .__str + other .__str
27+ else :
28+ return self .__str + other
29+
30+ def __sub__ (self , other ):
31+ "当与一个字符串或另一个String对象进行减操作时调用"
32+ if type (other ) is String :
33+ return self .__str - other .__str
34+ else :
35+ return self .__str - other
36+
37+ def isNumber (self ):
38+ "判断字符串是否由数字组成,返回布尔值"
39+ try :
40+ int (self .__str )
41+ except ValueError :
42+ return False
43+ else :
44+ return True
45+
46+ def toInt (self ):
47+ "如果能,将字符串转成整数,否则抛出NotComposedOfNumbersError异常"
48+ try :
49+ return int (self .__str )
50+ except ValueError as e :
51+ raise NotComposedOfNumbersError (
52+ "字符串不是由数字组成的"
53+ ) from e
54+
55+ def toInteger (self ):
56+ "如果能,将字符串转成Integer对象,否则抛出NotComposedOfNumbersError异常"
57+ try :
58+ return Integer (int (self .__str ))
59+ except ValueError as e :
60+ raise NotComposedOfNumbersError (
61+ "字符串不是由数字组成的"
62+ ) from e
63+
64+ class Integer :
65+ "整数类型,是对Python原版整数的加强"
66+ def __init__ (self , int_ ) -> None :
67+ if type (int_ ) is not int :
68+ raise TypeError (
69+ "请使用整数类型创建Integer对象"
70+ )
71+ self .__int = int_
72+
73+ def __repr__ (self ) -> str :
74+ return str (self .__int )
75+
76+ __str__ = __repr__
77+
78+ def __add__ (self , other ):
79+ "当与一个整数或另一个Integer对象进行加操作时调用"
80+ if type (other ) is Integer :
81+ return self .__int + other .__int
82+ else :
83+ return self .__int + other
84+
85+ def __sub__ (self , other ):
86+ "当与一个整数或另一个Integer对象进行减操作时调用"
87+ if type (other ) is Integer :
88+ return self .__int - other .__int
89+ else :
90+ return self .__int - other
91+
92+ def toStr (self ):
93+ "将整数转成字符串"
94+ return str (self .__int )
95+
96+ def toString (self ):
97+ "将整数转成String对象"
98+ return String (str (self .__int ))
0 commit comments