繁体   English   中英

Python中的__getitem__的许多级别

[英]Many levels of __getitem__ in Python

从另一个类中获取多个参数时该使用什么? 我需要类似getitem ()的东西,但是我只能得到1。

class Example(object):

    def __init__(self, ex1, ex2, ex3):
        self.ex1 = ex1
        self.ex2 = ex2
        self.ex3 = ex3
   #just example, this will not work
   def __getitem__(self, ex1, ex2, ex3):
   return self.ex1, self.ex2, self.ex3

Python兼有的多个参数[...]成元组:

class Example(object):

    def __init__(self, ex1, ex2, ex3):
        self.ex1 = ex1
        self.ex2 = ex2
        self.ex3 = ex3

    def __getitem__(self, index):
       ex1, ex2, ex3 = index
       return self.ex1, self.ex2, self.ex3

ex = Example(1,2,3)
print ex[1,2,3]

您需要这样做。

A.__getitem__()返回,另一个对象具有其自己的B.__getitem__()在该对象中返回C.__getitem()__ 那你可以做

b = a["1"]
c = b["2"]

这相当于说

 c = a["1"]["2"]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM