创建元组的三种方式、字典中的setdefault和get妙用、类中的重载方法__add__()

发布时间 2023-08-11 16:07:30作者: 等日落

创建元组的三种方式

# print(tuple([input(),input()]))
# print((input(),input()))
t = input(),input()
print(t)
# 可以将列表转换成tuple,也可以直接()创建tuple,或者将多个变量赋值给一个值会自动转换成tuple

字典中的setdefault和get妙用

setdefault类似get方法

w = input() #w是输入的一个字符串
d = {}
for i in w:
    d[i] = d.setdefault(i,0)+1
print(d)

dict.setdefault(k,v) 若有dict中存在k的key那么就返回对应的value,如果没存在,就将v的值赋给dict[k]并返回

get

word = input()

word_fre = {}

for i in word:

    word_fre[i] = word_fre.get(i,0) + 1

print(word_fre)

类中的重载方法__add__()

该方法用于由类实例化出来的对象进行相加时被调用!!!

class Coordinate(object):
    def __init__(self, x, y) -> None:
        self.x = x
        self.y = y

    def __str__(self) -> str:
        return '(%s,%s)' % (self.x, self.y)

    def __add__(self,other):
        return Coordinate(self.x + other.x, self.y + other.y)


x1, y1 = list(map(int, input().split()))
x2, y2 = list(map(int, input().split()))
c1 = Coordinate(x1, y1)
c2 = Coordinate(x2, y2)
print(c1 + c2)