简体   繁体   English

在python类中将整数作为静态变量引用

[英]Reference to integer as static variable inside python class

I'm trying to have a static int inside a class in python. 我正在尝试在python中的类中具有静态int。 But it doesn't work. 但这是行不通的。

Here's an example of what I've implemented : 这是我已实现的示例:

class MyDict(dict):

    STR_DEPTH = -1

    def __init__(self, **kwargs):
        super(MyDict, self).__init__(**kwargs)
        self.__dict__.update(name = kwargs.get("name", ""))

    def __str__(self):
        self.STR_DEPTH += 1
        res = self.name + '\n'
        for k in self.keys():
            res += '\t'*self.STR_DEPTH + k + " = "  + str(self[k])
            res += '\n'
        self.STR_DEPTH -= 1
        return res

def main():
    d1 = MyDict(one=MyDict())
    d1["two"] = 2
    d1["one"]["one"] = 1
    d1["one"]["two"] = MyDict(three=3)
    d1["four"] = 4
    print d1

if __name__ == "__main__":
    main()

and i'm expecting : 我期望:

four = 4
two = 2
one = 
    two = 
        three = 3

    one = 1

but it doesn't work that way. 但是那样行不通。 If i'm not mistaking, int aren't references and it's not the same "STR_DEPTH" in every instances of my class. 如果我没有记错的话,则int不是引用,并且在我的类的每个实例中都不是相同的“ STR_DEPTH”。

I already know the list-of-length-1 trick and the empty-type trick, but do i really need to resort do clumsy unreadable trick ? 我已经知道length-1列表技巧和空类型技巧,但是我真的需要采取笨拙的不可读技巧吗?

Isn't there a better way since i'm inside a class ? 自从我上课以来,有没有更好的方法?

Where you have: 您在哪里:

    self.STR_DEPTH += 1

replace that with: 替换为:

    MyDict.STR_DEPTH += 1

and the same where you decrement the value. 和您递​​减值的位置相同。

Assigning to self.STR_DEPTH will create a new instance variable which hides access to the class variable through self . 分配给self.STR_DEPTH将创建一个新的实例变量,该变量隐藏通过self对类变量的访问。 You can use self.STR_DEPTH to access the class variable provided you don't have an instance variable of the same name, but if you want to rebind the class variable you have to refer to it directly. 您可以使用self.STR_DEPTH来访问类变量,前提是您没有同名的实例变量,但是如果您想重新绑定该类变量,则必须直接引用它。

Note that self.STR_DEPTH += 1 is really just shorthand for self.STR_DEPTH = self.STR_DEPTH + 1 so even if the right hand self.STR_DEPTH picks up the class variable the assignment still happens back to the instance variable. 请注意, self.STR_DEPTH += 1实际上只是self.STR_DEPTH = self.STR_DEPTH + 1简写,因此,即使右手self.STR_DEPTH选择了类变量,分配仍会返回到实例变量。

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

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