pythonfileimportpython-import

Changing a variable in another file, with a function in that file


I have two files. file1 and file2.

file1:

color = (0, 0, 0)
class drawing:
    def changeColor(newColor):
        global color
        color = (newColor)
    def drawCircle(x, y, r, c=color)
        #circle draw function from pygame (not important)

file2:

from file1 import *
circle = drawing()
drawing.changeColor((255,255,255))
drawing.drawCircle(0, 0, 5)

and yet the circle still comes out black.

I've tried putting a print(color) command after the changeColor function, and it returns (0, 0, 0) too.

Assuming that my drawing function is correct, and my class definition is correct, is there anything else that I'm doing wrong?


Solution

  • You're encountering a common mistake related to Python's default argument values and how you are structuring your class and function usage.

    1. Default arguments are evaluated only once

    In your drawCircle method:

    def drawCircle(x, y, r, c=color)
    

    The default value of c is evaluated only once, at the time the function is defined, not each time it is called. So, even if you later change the global color, the function still uses the originally defined default (0, 0, 0).

    2. Improper use of global in class method

    You're using global color inside a method but color is not a truly global variable (from the perspective of the module importing it). Also, modifying globals this way is poor practice and can lead to confusing bugs.

    3. Method is not correctly defined as an instance or class method

    Your changeColor function is not an instance method because it lacks self and is not a @classmethod either. You're also calling it via the class name, which adds to the confusion.

    There's a way you can achieve this:

    # file1.py
    class Drawing:
        def __init__(self):
            self.color = (0, 0, 0)
    
        def changeColor(self, newColor):
            self.color = newColor
    
        def drawCircle(self, x, y, r):
            print(f"Drawing a circle at ({x}, {y}) with radius {r} and color {self.color}")
            # Add your pygame drawing code here using self.color
    
    # file2.py
    from file1 import Drawing
    
    circle = Drawing()
    circle.changeColor((255, 255, 255))
    circle.drawCircle(0, 0, 5)