Bhdr Bhdr - 19 days ago 6
Python Question

Assigning a function to a variable in Python

I have a function and I have to use more than one. When I assign to only one variable, everthing is OK. But when I assign to second variable or other, I just get last assignment result. How can I fix this.
Example:

def set_cnum(rpart, ipart):
set_cnum.rp = rpart
set_cnum.ip = ipart

a=set_cnum
b=set_cnum
a(30,40)
b(12,8)


print a.rp,a.ip


output

12 8

Answer

Instead of a function, use a class.

class setCnum:
    def __init__(self,rp, ip):
       self.rp = rp
       self.ip = ip

 a = setCnum(12, 8)
 print(a.rp) # Returns 12
 print(a.ip) # Returns 8