PCIL
PCIL

Reputation: 41

How to change a variable at function at Python

Assume that I have this code (at Python):

a=1
b=2
c=3

def x(a,b,c):
    a=5
    b=6
    c=7

x(a,b,c)
print(a,b,c)

The output will be: 1 2 3

My question is:
There is a why to change the values of a,b,c at x(a,b,c) (without return)?

Thank you!

Upvotes: 1

Views: 236

Answers (4)

aslattum
aslattum

Reputation: 1

So you can use the global modifier inside of the function to make the variables refer to the ones outside the function; however, this can result in a "code smell".

So inside the function, place global before those assignments and that should fix your problem.

Upvotes: 0

aquil.abdullah
aquil.abdullah

Reputation: 3157

As a new Python Programmer, PLEASE AVOID the use of global. Globals may be useful for things like configuration, but for the most part they can cause dangerous side effects if you start to use them as your default programming paradigm. I'd suggest you try a class pattern, or variable assignment pattern.

Class Assignment

class Foo(object):
    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

    def update(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

foo = Foo(1,2,3)
foo.update(5,6,7)
print "a: %d, b: %d, c: %d" % (foo.a, foo.b, foo.c)

Variable Assignment

a=1
b=2
c=3

def x():
    a_prime = 5
    b_prime = 6
    c_prime = 7
    return a_prime, b_prime, c_prime
a, b, c = x()
print a, b, c

Upvotes: 0

JkShaw
JkShaw

Reputation: 1947

A workaround would be to convert it into a list, as follows:

a = 1
b = 2
c = 3
l = [a, b, c]

def x(list):
    list[:] = [5, 6, 7]

x(l)

a, b, c = l
print(a, b, c)

Upvotes: 0

Laurent LAPORTE
Laurent LAPORTE

Reputation: 22992

Using the global keyword:

a=1
b=2
c=3

def x():
    global a, b, c
    a = 5
    b = 6
    c = 7

x()
print(a,b,c)
# -> 5 6 7

Using a class:

class Foo(object):
    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

    def x(self):
        self.a = 5
        self.b = 6
        self.c = 7


foo = Foo(1, 2, 3)
print(foo.a, foo.b, foo.c)
# -> 1 2 3

foo.x()
print(foo.a, foo.b, foo.c)
# -> 5 6 7

Upvotes: 2

Related Questions