|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
# !/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2023/2/20 21:48
# @Author : xiongming
# @File : duixiang-suoyin.py
# @Desc : 对象索引魔法方法
class C:
def __getitem__(self, index):
print(index)
c = C()
print(c[2])
c[2:8]
s = "I love FishC"
print(s[2:6])
print(s[slice(2, 6)])
print(s[7:])
print(s[slice(7, None)])
print(s[::4])
print(s[slice(None, None, 4)])
print("-----分隔符-----")
class D:
def __init__(self, data):
self.data = data
def __getitem__(self, index):
return self.data[index]
def __setitem__(self, index, value):
self.data[index] = value
d = D([1, 2, 3, 4, 5])
print(d[1])
d[1] = 11
print(d[1])
d[2:4] = [8, 7]
print(d[:])
class E:
def __init__(self, data):
self.data = data
def __getitem__(self, index):
return self.data[index] * 2
e = E([1, 2, 3, 4, 5])
for i in e:
print(i, end=' ')
print()
# 迭代器魔法方法
x = [1, 1, 2, 3, 5]
dir(x)
print("-----分隔符-----")
_ = iter(x)
while True:
try:
i = _.__next__()
except StopIteration:
break
print(i, end=' ')
print()
# 创造迭代器对象
class Double:
def __init__(self, start, stop):
self.value = start - 1
self.stop = stop
def __iter__(self):
return self
def __next__(self):
if self.value == self.stop:
raise StopIteration
self.value += 1
return self.value * 2
d = Double(1, 5)
for i in d:
print(i, end=' ') |
|