class MyStr():
def __init__(self,value):
self.value = value
def __str__(self):
return self.value
s1=MyStr('1')
print(s1)
1
- object.str(self): 生成一个对象的‘非正式’或者格式良好的字符串表示,返回值必须为字符串,如果上述1 是整数,则会报错:‘str returned non-string (type int)’
class MyStr():
def __init__(self,value):
self.value = value
def __add__(self, other):
return self.value+other.value*2
s1 = MyStr("1")
s2 = MyStr("2")
s1+s2
'122'
- 如上,object.add(self): 为重塑一个加法运算方法,可以是整数,也可以是字符串
class Vector:
def __init__(self, data):
self.data = data.copy()
def __add__(self, other):
v3_data = []
for ai, bi in zip(self.data, other.data):
v3_data.append(ai + bi)
return Vector(v3_data)
def __str__(self):
return str(self.data)
v1 = Vector([3, 4])
v2 = Vector([5, 6])
v3 = v1 + v2
print(v3)
[8, 10]