A bit of seasonal fun: how well do you know Python? #13256
Replies: 5 comments 6 replies
-
I think it will throw a HollidayException("The self.bar is not open yet") |
Beta Was this translation helpful? Give feedback.
-
Interesting. I would have said that it throws the moment the instance is created. |
Beta Was this translation helpful? Give feedback.
-
The code assigns Here an example: import time
class Foo:
_instances = set()
@property
def instances(self) -> int:
"""
Return the number of instances
"""
return len(self._instances)
def __init__(self, name):
# the static method __new__ could be
# used to modify the class before returning it
self._instances.add(self)
# alternative, if assignment is required
# cls = self.__class__
# cls._instances = 42
print(f"Foo has now {self.instances} instances")
self.name = name
self.timestamp = time.time()
# __del__ is not called in Micropython,
# but this works with CPython
def remove(self):
self._instances.remove(self)
print(f"Foo has now {self.instances} instances")
print(
f"Removed {self.name} from instances of Foo after {time.time() - self.timestamp:.2f} s"
)
print()
print("Instances of Foo:", Foo._instances)
f1 = Foo("First")
print("Instances of Foo:", Foo._instances)
print()
f2 = Foo("Second")
print("Instances of Foo:", Foo._instances)
print()
time.sleep(1)
f1.remove()
print("Instances of Foo:", Foo._instances)
print()
time.sleep(1)
f2.remove()
print("Instances of Foo:", Foo._instances) |
Beta Was this translation helpful? Give feedback.
-
O.K., another one:
will print what? |
Beta Was this translation helpful? Give feedback.
-
class K: pass
def a(o):
o.n **= 2
return o.n
def b(o,n):
o.n = int(n**(0.5))
return o.n
K.n = 2023; K.a = a; K.b = b
k0 = K()
print(k0.n == k0.b(k0.a()))
K.n = 2024
k1 = K()
print(k1.b(k1.a()) == k1.n)
print(k0.n == k1.n)
print(k0.n, '-->', k1.n) Merry Christmas and Happy New Year. |
Beta Was this translation helpful? Give feedback.
-
Can you predict what this will do? Will it throw, and if so on which line? Otherwise, what output will it produce?
This is not a MicroPython bug. Other simple Python gotchas welcome.
Beta Was this translation helpful? Give feedback.
All reactions