Home > Enterprise >  how to set a variable of a class from an other file in python
how to set a variable of a class from an other file in python

Time:11-10

Let's define two files :

test1.py

import test2

def doit():
    test2.var.a = 5

test2.py

class toto:
    def __init__(self):
        self.a = 1
        self.b = 10
        self.c = 0

    def func(self):
        self.c = self.a   self.b
        print(self.c)

global var
var = toto()
def main():

    print('start')
    var.func() # compute 1   10 = 11
    test1.doit() # change value of a
    var.func() # shall compute 5   10 = 15 but still 11

    r=1 #for breakpoint


if __name__ == '__main__':
    main()

I do not achieve to set the variable var.a from test1.py. It sounds like the class is duplicated in memory rather than adressing the one already instantiated. Any idea ?

thanks & cheers

Stephane

CodePudding user response:

It is wrong idea to change value in this way.

You should send object explicitly as argument - and then you don't need to import, and code is more readable, and it is also simpler to debug.

And this is suggested by The Zen of Python: Explicit is better than implicit.

def doit(item):
    item.a = 5

and later

doit(var)

PEP 20 -- The Zen of Python


test1.py

# no need to import

def doit(item):
    item.a = 5

test2.py

import test1

class Toto:  # PEP8: `CamelCaseNames` for classes
    def __init__(self):
        self.a = 1
        self.b = 10
        self.c = 0

    def func(self):
        self.c = self.a   self.b
        print(self.c)

def main():
    var = Toto()

    print('start')

    var.func()  # compute 1   10 = 11
    doit(var)   # change value of a
    var.func()  # shall compute 5   10 = 15 but still 11

    r = 1  # for breakpoint

if __name__ == '__main__':
    main()
  • Related