简体   繁体   English

如何从 class 中更改 class 变量值?

[英]How to change class variable value from within the class?

I am fairly new to python, and currently working on a project.我对 python 相当陌生,目前正在从事一个项目。 Following is my Dimension class:以下是我的尺寸 class:

class Dimension:
    dpi = 0
    padding_x = 200 * dpi
    padding_y = 100 * dpi

I am setting the dpi value from another class called Splash:我正在从另一个名为 Splash 的 class 设置 dpi 值:

class Splash:
if __name__ == '__main__':
    Dimension.dpi = 1.6
    print("x padding : {}".format(Dimension.padding_x))  # prints 0

So my problem is, while I get the value of dpi as 1.6 if I try to print it, the corresponding value of padding_x or padding_y is 0 even after I have set dpi value.所以我的问题是,当我尝试打印它时,我将 dpi 的值设为 1.6,即使我设置了 dpi 值,padding_x 或 padding_y 的相应值也是 0。 When the variable dpi's value is changed, shouldn't the padding_x or y's value also be changed?当变量 dpi 的值改变时,padding_x 或 y 的值不应该也改变吗?

You declared dpi to be 0 and because you are using these variables as static variables it will retain its original values.您将 dpi 声明为 0,并且因为您将这些变量用作 static 变量,所以它将保留其原始值。 Static variables retain value regardless of the instance of the object.无论 object 的实例如何,Static 变量都会保留值。 What you should do is:你应该做的是:

class Dimension:
    dpi = 0
    padding_x = 200
    padding_y = 100
    def __init__(self):
        self.padding_x = self.padding_x*self.dpi

class Splash:
    if __name__ == '__main__':
        Dimension.dpi = 1.6
        a = Dimension()
        print("x padding : {}".format(a.padding_x))

you can still use the dpi as a static variable but it would be better to utilize the constructor toinitialize the other variables您仍然可以将 dpi 用作 static 变量,但最好使用构造函数来初始化其他变量

if you still want to use as static the do this:如果您仍想用作 static,请执行以下操作:

class Dimension:
    dpi = 0
    padding_x = 200
    padding_y = 100

class Splash:
    if __name__ == '__main__':
        Dimension.dpi = 1.6;
        Dimension.padding_x=200*Dimension.dpi
        print("x padding : {}".format(Dimension.padding_x)) 

using a static method to change the values:使用 static 方法更改值:

class Dimension:
    dpi = 0
    padding_x = 200
    padding_y = 100
    @staticmethod
    def static(dpi):
        Dimension.dpi = dpi
        Dimension.padding_x *= Dimension.dpi
        Dimension.padding_y *= Dimension.dpi
class Splash:
    if __name__ == '__main__':
        Dimension.static(1.6);
        print("x padding : {}".format(Dimension.padding_x)) 

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

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