gpt4 book ai didi

python - 如何使用 [] 为新类定义选择?

转载 作者:行者123 更新时间:2023-11-28 22:30:37 26 4
gpt4 key购买 nike

我创建了一个新类,我想定义如何使用 [] 从中选择内容。有办法吗?

class NewClass:
def __init__(self, list):
self.list_item = list

# def __indexer__(self, slice_object):
# return list[slice_object]

example = NewClass(range(0, 5))
print example[0:3]

最佳答案

当然,它叫做 __getitem__ .

class NewClass(object):
def __init__(self, list):
self.list_item = list
def __getitem__(self, slice_object):
return self.list_item[slice_object]

example = NewClass(range(0, 5))
print(example[0:3])

关于python - 如何使用 [] 为新类定义选择?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42067365/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com