繁体   English   中英

别名不带dict的python变量

[英]Aliasing python variables without dict

我只是在实现一个类,该类需要一个属性来将另一个属性的引用存储为游标。 请参阅以下内容:

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方式可以实现上述self.spam

你可以存储在索引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

暂无
暂无

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

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