简体   繁体   中英

How to change class variable value from within the class?

I am fairly new to python, and currently working on a project. Following is my Dimension class:

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

I am setting the dpi value from another class called Splash:

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. When the variable dpi's value is changed, shouldn't the padding_x or y's value also be changed?

You declared dpi to be 0 and because you are using these variables as static variables it will retain its original values. Static variables retain value regardless of the instance of the object. 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

if you still want to use as static the do this:

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:

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)) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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