I'm trying to figure out how to change some value after each call of the object.
I thougt that call() function is executed after each call.
This should be a simple counter class which decreases value attribute after being called.
class counter():
def __init__(self,value):
self.value = value
def __call__(self):
self.value -= 1
count = counter(50)
print count.value
print count.value
>> 50
>> 50 <-- this should be 49
What am I doing wrong?
If you're not committed to classes, you could use a function and abuse using mutable-types-as-default-initializers:
def counter(init=None, container=[0]):
container[0] -= 1
if init is not None: container[0] = init
return container[0]
x = counter(100)
print(x) # 100
print( counter() ) # 99
print( counter() ) # 98
print( counter() ) # 97
# ...
Call counter with a single argument to set/initialize the counter. Since initialization is actually the first call to the function, it will return that number.
Call counter with no arguments to get the "next value".
(Very similar to what I suggested here)
Alternatively, for a syntax closer to what you had in your question, use properties:
class Counter(object):
def __init__(self, init):
self.val = init
#property
def value(self):
val = self.val
self.val -= 1
return val
count = Counter(50)
print(count.value) # 50
print(count.value) # 49
print(count.value) # 48
print(count.value) # 47
#...
Here, you're creating a Counter object called count, then every time you call count.value it returns the current value and prepares itself for a future call by decrementing it's internal val attribute.
Again, the first time you request the value attribute, it returns the number you initialized it with.
If, for some reason, you want to "peek" at what the next call to count.value will be, without decrementing it, you can look at count.val instead.
__call__ is only invoked when you call the object using ()
To invoke this behaviour you'd have to do
class counter():
def __init__(self,value):
self.value = value
def __call__(self):
print 'called'
self.value -= 1
count = counter(50)
print count.value
count()
print count.value
This may not be exactly what you wanted to do.
Use the property decorator
class counter:
def __init__(self, value):
self._value = value + 1
#property
def value(self):
self._value -= 1
return self._value
count = Counter(50)
print(count.value) # 50
print(count.value) # 49
Alternatly, you could use a closure:
def Counter(n):
n += 1
def inner():
n -= 1
return n
return inner
Though this has to be called every time you want to use it
count1 = Counter(50)
count2 = Counter(50)
print(count1()) # 50
print(count1()) # 49
print(count2()) # 50
print(count2()) # 49
print(count1()) # 48
Defining a custom call() method in the meta-class allows custom behaviour when the class is called, e.g. not always creating a new instance.As no new class instance is created call gets called instead of init.So do this to get the desired result
print count.value
count()
print count.value
Related
Define a class for a type called CounterType. An object of this type is used to count
things, so it records a count that is a nonnegative whole number.
a. Private data member: count.
b. Include a mutator function that sets the counter to a count given as an argument.
c. Include member functions to increase the count by one and to decrease the count
by one.
d. Include a member function that returns the current count value and one that outputs
the count.
e. Include default constructor that set the count to 0.
f. Include one argument constructor that set count to given argument.
Be sure that no member function allows the value of the counter to become negative.
Embed your class definition in a test program.
An output example would be:
a = CounterType(10)
a.display()
a.increase()
a.display()
a.setCounter(100)
a.display
Will display the following:
Counter: 10
Counter: 11
Counter: 100
I have written the code but I just want to make sure that it is following what the question asked and if there could be an easier way to write this code.
class CounterType:
def __init__(self, counter=0):
self.counter = counter
def increase(self):
self.counter += 1
def decrease(self):
if self.counter == 0:
print("Error, counter cannot be negative")
else:
self.counter -= 1
def setCounter(self, x):
if x < 0:
print("Error, counter cannot be negative")
else:
self.counter = x
def setCount0(self):
self.counter = 0
def display(self):
print("Counter:", self.counter)
def getCounter(self):
return self.counter
This is a homework assignment so it would help if you could just give some tips
You forgot "Be sure that no member function allows the value of the counter to become negative."
The naïve way to do this is to add an if condition in every function. A smarter way would be to add that check the setCounter function and use this function from all other functions.
class CounterType:
def __init__(self, counter=0): # (e, f) counter = 0: default argument value so x = CounterType() works and has a counter of 0
self.counter = 0 # (a)
self.setCounter(counter)
def increase(self): # (c)
self.setCounter(self.counter + 1)
def decrease(self): # (c)
self.setCounter(self.counter - 1)
def setCounter(self, x): # (b)
if x < 0:
print("Error, counter cannot be negative")
else:
self.counter = x
def setCount0(self): # This is not needed
self.counter = 0
def display(self): # (d)
print("Counter:", self.counter)
def getCounter(self): # (d)
return self.counter
add_digits2(1)(3)(5)(6)(0) should add up all the numbers and stop when it reaches 0.
The output should be 15
The below code works but uses a global variable.
total = 0
def add_digits2(num):
global total
if num == 0:
print(total)
else:
total += num
return add_digits2
The result is correct but needs to do the same thing without using the global variable.
One thing you could do is use partial:
from functools import partial
def add_digits2(num, total=0):
if num == 0:
print(total)
return
else:
total += num
return partial(add_digits2, total=total)
add_digits2(2)(4)(0)
You can just pass in *args as a parameter and return the sum
def add_digits2(*args):
return sum(args)
add_digits2(1, 3, 5 ,6)
You could also use a class, using the __call__ method to obtain this behavior:
class Add_digits:
def __init__(self):
self.total = 0
def __call__(self, val):
if val != 0:
self.total += val
return self
else:
print(self.total)
self.total = 0
add_digits = Add_digits()
add_digits(4)(4)(0)
# 8
add_digits(4)(6)(0)
# 10
though I still don't get why you would want to do this...
Really hard to say what they are after when asking questions like that but the total could be stored in a function attribute. Something like this
>>> def f():
... f.a = 3
>>> f()
>>> f.a
3
I am recursively generating few objects, which need a contiguous, unique id. How can I guarantee (easiest) the synchronization in python 2.7.
iid = 1
def next_id():
iid += 1
return iid
def process():
# .. do something
id = next_id()
from itertools import count
iid = count()
print next(iid) # 0
print next(iid) # 1
print next(iid) # 2
etc., and
new_iid = count(10)
print next(new_iid) # 10
print next(new_iid) # 11
print next(new_iid) # 12
for starting at other values than 0.
count() is essentially a generator which infinitely yields values.
Use a mutex:
import threading
iid = 1
iid_lock = threading.Lock()
def next_id():
global iid
with iid_lock:
result = iid
iid += 1
return result
You might like to hide the internals in a class:
class IdGenerator(object):
def __init__(self):
self.cur_id = 1
self.lock = threading.Lock()
def next_id(self):
with self.lock:
result = self.cur_id
self.cur_id += 1
return result
EDIT: Based on the comments, it seems like you're not using threads. This means you don't need the locking mechanism at all. What you initially wrote would be sufficient, though you need the global keyword to make the global variable mutable:
iid = 1
def next_id():
global iid
res = iid
iid += 1
return res
You were thinking to something of this kind:
class Counter():
def __init__(self):
self.theCount = -1
def __call__(self):
self.theCount += 1
return self.theCount
class BorgCounter():
Borg = {'theCount':-1}
def __init__(self):
self.__dict__ = BorgCounter.Borg
def __call__(self):
self.theCount += 1
return self.theCount
myCount = Counter()
mycount2 = Counter()
assert(myCount()==0)
assert(mycount2()==0)
assert(mycount2()==1)
assert(myCount()==1)
assert(myCount()==2)
myCount = BorgCounter()
mycount2 = BorgCounter()
assert(myCount()==0)
assert(mycount2()==1)
assert(mycount2()==2)
assert(myCount()==3)
assert(myCount()==4)
I have a class defined like so:
class GameState:
def __init__(self, state=None):
if state is None:
self.fps = 60
self.speed = 1
self.bounciness = 0.9
self.current_level = None
self.next_frame_time = 0
self.init_time = 0
self.real_time = 0
self.game_time = 0
self.game_events = []
self.real_events = []
else:
# THIS being the key line:
self.__dict__.update(**state)
Is there an interface I can define, such that this works (i.e. the ** operator works on my class):
>>> a = GameState()
>>> b = GameState(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: update() argument after ** must be a mapping, not GameState
Essentially, I want b to take on all of the attributes of a.
I didn't think it would work, but I tried defining __getitem__ without any luck.
EDIT: I want to avoid using b's __dict__, as I want to also be able to pass a dictionary as an argument, and potentially use ** on GameState objects elsewhere.
let GameState inherit from dict :
class GameState(dict)
and rewrite the __setattr function like this :
def __setattr__(self,name,value) :
self.__dict__[name] = value
self[name] = value
in order for **obj to work, you have to implement (or inherit) the __getitem__() and keys() methods.
def __getitem__(self, item):
return self.__dict__[item] # you maybe should return a copy
def keys(self):
return self.__dict__.keys() # you could filter those
you could do that by updating the b's dict with that of a when creating b. Try this out:
class GameState:
def __init__(self, state=None):
if state is None:
self.fps = 60
self.speed = 1
self.bounciness = 0.9
self.current_level = None
self.next_frame_time = 0
self.init_time = 0
self.real_time = 0
self.game_time = 0
self.game_events = []
self.real_events = []
else:
if type(state) is dict:
self.__dict__.update(**state)
else:
self.__dict__.update(**state.__dict__)
a = GameState()
b = GameState(a)
you might want to create a deepcopy of the dict because you have a list object as part of the attributes. This is safer as there is no sharing of objects.
I have an iterator with a __len__ method defined. Questions:
If you call list(y) and y has a __len__ method defined, then __len__ is called.
1) Why?
In my output, you will see that the len(list(y)) is 0 on the first try. If you look at the list output, you will see that on the first call, I receive an empty list, and on the second call I receive the "correct" list.
2) Why is it returning a list of length zero at all?
3) Why does the list length correct itself on all subsequent calls?
Also notice that calling "enumerate" is not the issue. Class C does the same thing but using a while loop and calls to next().
Code:
showcalls = False
class A(object):
_length = None
def __iter__(self):
if showcalls:
print "iter"
self.i = 0
return self
def next(self):
if showcalls:
print "next"
i = self.i + 1
self.i = i
if i > 2:
raise StopIteration
else:
return i
class B(A):
def __len__(self):
if showcalls:
print "len"
if self._length is None:
for i,x in enumerate(self):
pass
self._length = i
return i
else:
return self._length
class C(A):
def __len__(self):
if showcalls:
print "len"
if self._length is None:
i = 0
while True:
try:
self.next()
except StopIteration:
self._length = i
return i
else:
i += 1
else:
return self._length
if __name__ == '__main__':
a = A()
print len(list(a)), len(list(a)), len(list(a))
print
b = B()
print len(list(b)), len(list(b)), len(list(b))
print
c = C()
print len(list(c)), len(list(c)), len(list(c))
Output:
2 2 2
0 2 2
0 2 2
If you call list(y) and y has a
len method defined, then len is called. why?
Because it's faster to build the resulting list with the final length, if known from the start, than to begin with an empty list and append one item at a time. And __len__ is, and must be, 100% guaranteed to be reliable.
IOW, do not implement special methods like __len__ if and when you can't return a reliable value.
As for the second question, your implementations of __len__ are broken because they consume the iterator (and don't return it to its pristine state) -- so they leave no items for following .next calls, so the list constructor gets a StopIteration and decides that your __len__ was just flaky (it's unfortunately flakier than poor list can guess...!-).