This question already has answers here:
How to have multiple inits for a class
(4 answers)
Closed last year.
Hi in a recent local programming contest there was a problem in which you had to define a class which takes chain-like parameters and returns their sum e.g. :
>>> Chain(2.5)(2)(2)(2.5) # sum
9
>>> Chain(3)(1.5)(2)(3) # sum
9.5
Best thing that I could write is this code:
class Chain():
value = 0
def __new__(self, num):
self.value += num
return self
obj = Chain(2)(3)
print(obj.value)
But the return type is a class not an int, furthermore I'm using a static property which is obviously wrong. Would appreciate any helps.
P.S. : Please note that that contest finished on January 7 2022 so I don't think there is any problem with posting this question.
You can inherit from float (as you need to support decimal numbers) and implement __call__ like so:
class Chain(float):
def __call__(self, value):
return self.__class__(self+value)
>>> Chain(3)(1.5)(2)(3) # sum
9.5
>>> Chain(2.5)(2)(2)(2.5) # sum
9.0
This question already has answers here:
Function closure vs. callable class
(6 answers)
Closed 2 years ago.
Is either of the two styles preferred or more "pythonic" for creating closures (edit: "closure-like objects")?
def make_doer(closed_var):
def doer(foo):
pass # Do something with closed_var and foo
return doer
class Doer:
def __init__(self, closed_var):
self._closed_var = closed_var
def __call__(self, foo):
pass # Do something with self._closed_var and foo
The only differences I can tell are that the former is a tiny bit shorter but the second has an advantage in that the docstring for the resulting function (__call__ in the second case) is less nested/hidden. Neither seems like a huge deal, anything else that would tip the balance?
Closures have to do with maintaining references to objects from scopes that have passed, or from earlier scopes.
Here is the simplest example of the form a Closure takes:
def outer():
x=7
def inner(y):
return x + y
return inner
i = outer()
This question already has answers here:
What does it mean when the parentheses are omitted from a function or method call?
(6 answers)
Closed 4 years ago.
So I got stuck on something like this (a simplified version)
class Node:
def __init__(self):
self.left= None
self.cost = 0
def change(self):
if self.left is not None:
self.left.cost=self.cost+1
self.left.change
data=[]
for i in range(10):
data.append(Node())
if i>0:
data[i].left = data[i-1]
data[8].change()
print(data[2].cost) #0
I want data[2].cost to have changed, but it rollbacks. Can I make it works without skipping recursion? (In full version I actually keep a two-dimensional array of nodes that have four pointers, so making an iteration suck.)
You forgot () when you call your change method.
def change(self):
if self.left is not None:
self.left.cost=self.cost+1
self.left.change()
output:
6
Obviously you want to call change but you didn't. You just refered to the function object and did nothing with it.
Just change self.left.change to self.left.change() to call it
This question already has answers here:
Python Argument Binders
(7 answers)
Closed 6 months ago.
We have the following function call used at multiple places within close proximity:
func(param1, param2, param3, param4, param5)
I would like to use
funccall()
in all the places.
Is there a notion of macros? Partials with all the arguments given (marked answer as correct) is correct and it works if all the subsequent calls are in the same scope.
What if the scenario is like this:
A():
func(p1,p2,p3,p4,p5) # 3 times
B():
func(p1,p2,p3,p4,p5) # 2 times
C():
func(p1,p2,p3,p4,p5) # 4 times
Using partial:
A():
funccall = partial(func,p1,p2,p3,p4,p5)
funccall() # 3 times
B():
funccall = partial(func,p1,p2,p3,p4,p5)
funccall() # 2 times
C():
funccall = partial(func,p1,p2,p3,p4,p5)
funccall() # 4 times
Ideal (if convention is followed in code and readability is not a problem)
macro funccall() = func(p1,p2,p3,p4,p5)
A():
funccall() # 3 times
B():
funccall() # 2 times
C():
funccall() # 4 times
This question is related to this one
As the answer provided by MattH, you can use functools.partial
from functools import partial
funccall = partial(func, 1, 2, 3, 4, 5)
funccall()
set default parameters and only call the function explicitely with those parameters which are different from the default parameters!
e.g. def func(param1=0, param2="abc", param3=0.3) for definition
and result = func(param1=3) when calling.
(not tested, but I see no reason why this shouldn't work!)
This question already has answers here:
What is the purpose and use of **kwargs? [duplicate]
(13 answers)
Closed 7 years ago.
I'm testing to use kwargs and have a trouble.
This is the python3 code :
class B:
def __init__(self, **kwargs):
print(kwargs['city'])
a = {'phone':'0101', 'city':'Daejeon'}
b = B(a)
But, there is an error like below :
b = B(a)
TypeError: __init__() takes 1 positional argument but 2 were given
Is there something wrong in my code?
I think that I just exactly follow the tutorial....
Keyword arguments are not passed that way.
obj1 = B(phone='0101', city='Daejeon')
obj2 = B(**a)