python 成员关系:__contains__,__iter__和__getitem__

#__contains__优于__iter__优于__getitem__方法
#__contains__方法应该把成员关系定义为对一个映射应用键(并且可以使用快速查找),以及用于序列的搜索

class Iters:
    def __init__(self, value):
        self.data=value
    def __getitem__(self, i):   
        print('get[%s]:'%i, end=' ')
        return self.data[i]

    def __iter__(self):
        print('iter=>', end=' ')
        self.ix=0
        return self

    def __next__(self):
        print('next:', end=' ')
        if self.ix==len(self.data):
            raise StopIteration
        item=self.data[self.ix]
        self.ix+=1
        return item

    def __contains__(self, x):    #in操作
        print('contains: ',end=' ')
        return x in self.data

    
x=Iters([1,2,3,4,5])
print(3 in x)    #contains:  True
for i in x:
    print(i, end=', ')    #iter=> next: 1, next: 2, next: 3, next: 4, next: 5, next:
print()
print([i**2 for i in x])    #iter=> next: next: next: next: next: next: [1, 4, 9, 16, 25]
print(list(map(bin,x)))    #iter=> next: next: next: next: next: next: ['0b1', '0b10', '0b11', '0b100', '0b101']
i=iter(x)
while True:
    try:
        print(next(i), end=' @ ')    #iter=> next: 1 @ next: 2 @ next: 3 @ next: 4 @ next: 5 @ next:
    except StopIteration:
        break
print()   
print(x[0])    #get[0]: 1   __getitem__支持索引
print(x[:-1])    #get[slice(None, -1, None)]: [1, 2, 3, 4]
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
`__dir__` 是一个特殊方法(也称为魔术方法或魔法方法),用于定义一个对象的自定义 `dir()` 行为。当使用内置函数 `dir()` 来获取一个对象的属性和方法列表时,如果该对象定义了 `__dir__` 方法,Python 会调用该方法来获取列表。 例如,假设有一个自定义的类 `MyClass`,我们可以在该类中定义 `__dir__` 方法来返回自定义的属性和方法列表。下面是一个示例: ```python class MyClass: def __dir__(self): return ['attr1', 'attr2', 'method1', 'method2'] obj = MyClass() print(dir(obj)) ``` 输出结果为: ``` ['attr1', 'attr2', 'method1', 'method2'] ``` 可以看到,我们在 `MyClass` 类中定义了 `__dir__` 方法,该方法返回了一个自定义的属性和方法列表。当调用 `dir(obj)` 时,Python 会调用 `obj.__dir__()` 方法来获取列表。 另一方面,`dir()` 是一个内置函数,用于获取一个对象的属性和方法列表。当我们调用 `dir(obj)` 时,Python会返回该对象所有可用的属性和方法的名称列表。 ```python obj = [1, 2, 3] print(dir(obj)) ``` 输出结果为: ``` ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] ``` 可以看到,`dir(obj)` 返回了一个包含列表对象 `obj` 的所有属性和方法名称的列表。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值