user3565150
user3565150

Reputation: 914

Python static variable generator function

I am using the following function to generate a static variable in Python:

 #Static variable generator function
def static_num(self):
    k = 0
    while True:
        k += 1
        yield k

When I am calling this function from main code:

 regression_iteration = self.static_num()
 print " Completed test number %s  %s \n\n" % (regression_iteration, testname)

I get this output:

  "Completed test number <generator object static_num at 0x027BE260>  be_sink_ncq"

Why I am not getting an incremented integer? Where is my static variable generator going wrong?

Edit:

I am calling the function static_num in the following manner now:

regression_iteration = self.static_num().next()

But it returns only '1' since the value of 'k' is being initialized to zero every time the function is called. Therefore, I do not get the required output 1,2,3,4 .... on every call of the function

Upvotes: 2

Views: 2914

Answers (3)

Matt
Matt

Reputation: 744

Assuming that by static you meant static to the class, the best way to do this is to use a class variable and a classmethod:

class Static_Number_Class(object):
    _static_number = 0
    @classmethod
    def static_number(cls):
        cls._static_number += 1
        return cls._static_number

If this is just a stand alone function you could use a closure instead:

def Counter():
    n = 0
    def inner():
        n += 1
        return n
    return inner

count = Counter()
x = count()
print(x) # 1
x = count()
print(x) # 2

Upvotes: 0

jedwards
jedwards

Reputation: 30240

Its hard to say whether you need to use this approach -- I strongly doubt it, but instead of a generator you could abuse using mutable types as default initializers:

def counter(init=[0]):
    init[0] += 1
    return init[0]

x = counter()
print(x)  # 1
print(x)  # 1
print(x)  # 1
x = counter()
print(x)  # 2
print(x)  # 2
print(x)  # 2
# ... etc

The return value of counter increases by one on each call, starting at 1.

Upvotes: 4

amow
amow

Reputation: 2223

The yield keyword convert your function return value from int to an int generator, so you have to use "for i in self.static_num()" to access the int.If you want to access the generator one by one. Use next function.

Upvotes: 0

Related Questions