+ 6

Does the walrus operator work for functions(methods) too?

In Python all is object. So if wo:= 3 or wo:=str.center should not matter. but I dont get it. I cant create a program for it. yeah there are lambdas, but I WANT WALRUS. EDIT: I wanted center(20) as walrus .... see prog https://code.sololearn.com/c2hdaPD1J8iC/?ref=app

30th Dec 2022, 8:02 AM
Oma Falk
Oma Falk - avatar
7 Respuestas
+ 7
I think you are looking for something like this. You can bind a lambda which will center a piece of text, to a variable with walrus, then reuse the same lambda later. print((y := lambda t: t.center(20))("hello"), y("world"), sep="\n")
30th Dec 2022, 9:46 AM
Tibor Santa
Tibor Santa - avatar
+ 4
Denise Roßberg tbh: I wanted center(50) as a walrus... i dont want to define before but inline .... Now I can say clearly what the problem is.
30th Dec 2022, 9:04 AM
Oma Falk
Oma Falk - avatar
+ 3
Hi Oma Falk Do you mean something like this? def fun(): print('test') (walrus:=fun) walrus()
30th Dec 2022, 8:45 AM
Denise Roßberg
Denise Roßberg - avatar
+ 3
independent of the walrus operator: if you only store the method center, I wonder how a string should access it. x = str.center And now? "abc".x(20) will not work, because str does not know x.
30th Dec 2022, 9:25 AM
Denise Roßberg
Denise Roßberg - avatar
+ 3
If you do... x := str.center ... you are storing the type's original method. Using that, you would have to pass 'self' by hand, because x is not an instance method. So you'd have to use... x('your string', 42) ... instead of just ... x(42) I can imagine hacks like this one, just to illustrate: print((x := str.center)('hello', 9), x('world', 9)) Alternatively, you can store the instance method as well, but then you can only call it for that specific str object. print([x:='Hello'.center, x(7)][1], x(9), x(11), sep='\n') Here, first the string 'Hello' is created, its method center bound to the name x, and then the method is called several times for the object it belongs to.
31st Dec 2022, 12:48 PM
HonFu
HonFu - avatar
+ 2
works also: st = "test" (wo:=st.center(50)) print(wo) Unfortunately I forgot where I have read that walrus operator needs brackets. Normally you use it inside an expression, maybe it has something to do with that.
30th Dec 2022, 9:10 AM
Denise Roßberg
Denise Roßberg - avatar
+ 1
(w:=lambda x,y:x.center(y)) do you mean something similar to this? or like (p:=print)
31st Dec 2022, 5:38 PM
Just Some Random Guy
Just Some Random Guy - avatar