BrightXiong 发表于 2023-2-20 22:21:58

对象索引魔法方法

# !/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)
c
s = "I love FishC"
print(s)
print(s)

print(s)
print(s)

print(s[::4])
print(s)

print("-----分隔符-----")

class D:
    def __init__(self, data):
      self.data = data
    def __getitem__(self, index):
      return self.data
    def __setitem__(self, index, value):
      self.data = value

d = D()

print(d)
d = 11
print(d)
d =
print(d[:])

class E:
    def __init__(self, data):
      self.data = data
    def __getitem__(self, index):
      return self.data * 2

e = E()
for i in e:
    print(i, end=' ')

print()

# 迭代器魔法方法
x =
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=' ')
页: [1]
查看完整版本: 对象索引魔法方法