簡體   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