2016-03-05 129 views
1

我只是實現一個需要一個屬性來存儲另一個屬性的引用作爲遊標的類。請參閱以下內容:別名字典的別名python變量

class foo: 
    def __init__(self): 
     self.egg=[4,3,2,1,[4,3,2,1]] 
     self.spam=#some reference or pointer analog represent self.egg[4][2], for example 

    def process(self): 
     # do something on self.egg[self.spam] 
     pass 

我不想dict因爲self.spam只能代表一個項目,並使用dict我將不得不無限期消耗不必要的內存。上面有沒有實現self.spam的pythonic方法?

回答

1

你可以索引存儲在self.spam,並使用屬性從self.egg訪問值給出的self.spam當前值:

class Foo(object): 
    def __init__(self): 
     self.egg = [4,3,2,1,[4,3,2,1]] 
     self.spam = (4,2) 

    def process(self): 
     # do something on self.egg[self.spam] 
     print(self.eggspam) 
     pass 

    @property 
    def eggspam(self): 
     result = self.egg 
     for item in self.spam: 
      result = result[item] 
     return result 

f = Foo() 
f.process() 
# 2 

f.spam = (1,) 
f.process() 
# 3