+ 1
[solved] Python Unary * and **
Can "*" and "**" unary operators be redefined using "magic" methods? Tried to quick Google, but did not find answer. Example I was experimenting with: https://code.sololearn.com/c5ac65WxNnk2/?ref=app
11 odpowiedzi
+ 2
to implement Mapping behavior, you should inherit from collections.abc.Mapping and implement __iter__ (keys), __getattr__ (values) and __len__ (length):
import collections.abc
class UnpackableObject(collections.abc.Mapping):
def __iter__ (self):
for i in range(1, 5): yield i
def __getitem__(self,prop):
return 'abcd'[prop-1]
def __len__(self):
return 4
print((*UnpackableObject(),))
print({**UnpackableObject()})
+ 1
Hi! to the best of my understanding of your question, as far as I know, the * operator is multiplication, and * * is exponentiation. what do you mean by magic methods?
+ 1
Ярослав Вернигора(Yaroslav Vernigora), in Python magic methods are methods which are internally called when using operators on that objects (for example, "x == y" => "x.__eq__(y)" or (if x.__eq__ is not implemented) "y.__req__(x)") or when passing them as parameters of some built-in functions (for example, "len(x)" => "x.__len__()"). See https://www.sololearn.com/learning/2470/ and/or Intermediate Python, OOP, lesson 22.1 "Magic Operators & Operator Overloading".
"*" and "**" operators (when there is no left operand) are used to "unpack" the list and dictionary (dict) respectively.
+ 1
That's it, I understand the question. this applies to unary operators. this topic was not clear to me even when studying the javascript.
+ 1
Ярослав Вернигора(Yaroslav Vernigora), OK (I am sorry that it is happening to you), my question now is: how to make class a mapping (do I need to create new question for this)?
+ 1
hint: post new questions in a newly created thread. so more chances to be seen
+ 1
Hi! you can help yourself with this. carefully read and complete the lesson that explains how to escape characters in a text string
+ 1
Thanks brother!
0
unfortunately, direct links to the lesson pages do not work for some reason. the app freezes
- 1
I experimented with code and discovered that unary "*" operator is actually (maybe, modified) "__iter__" method, but I cannot figure out how to make class objects mappings (for "**").
- 1
print('I'm learning Python!')
print("A number enclosed in double quotes: "42"")
Fix the given Python code to generate the expected output.
Who gives me a hand with this problem?