Is it possible to call a class but without a new instance created?
Peter Otten
__peter__ at web.de
Mon Jun 18 04:27:30 EDT 2018
Jach Fong wrote:
> Is it possible to call a class but without a new instance created?
Yes, this is possible in Python, by writing a custom __new__ method. An
extreme example:
>>> class Three:
... def __new__(*args): return 3
...
>>> a = Three()
>>> b = Three()
>>> a
3
>>> b
3
>>> a is b
True
But this is not what is done with the tkinter Font class. Most tkinter
classes refer to a tcl/tk object and so does Font.
import tkinter as tk
from tkinter.font import Font
root = tk.Tk()
a = Font(root, name="foo", size=10, exists=False)
label = tk.Label(root, text="hello", font=a)
label.pack()
def update_foo():
b = Font(root, name="foo", size=20, exists=True)
# two distinct Font objects referring to the same underlying tcl font.
assert a is not b
button = tk.Button(root, text="update foo font to 20pt", command=update_foo)
button.pack()
root.mainloop()
Here the b = Font(...) creates another wrapper for the "foo" font and
updates its size in the process so that the label's appearance is updated,
too.
More information about the Python-list
mailing list