On 2024-02-17 22:35, Jonathan Gossage via Python-list wrote:
I am attempting to use the __new__ method in the following code:
class SingletonExample(object):
_instance = None
def __new__(cls, **kwargs):
if cls._instance is None:
cls._instance = super().__new__(cls, **kwargs)
return cls._instance
def __init__(self, **kwargs) -> None:
our_attributes = ('h', 'x')
if kwargs is not None:
for k, v in kwargs.items():
if k in our_attributes:
setattr(self, k, v)
a = SingletonExample(h=1)
and I get the following result:
(PRV) jonathan@jfgdev:/PR$ python -m Library.Testing.test2
Traceback (most recent call last):
File "<frozen runpy>", line 198, in _run_module_as_main
File "<frozen runpy>", line 88, in _run_code
File "/mnt/ProgrammingRenaissance/Library/Testing/test2.py", line 16, in
<module>
a = SingletonExample(h=1)
^^^^^^^^^^^^^^^^^^^^^
File "/mnt/ProgrammingRenaissance/Library/Testing/test2.py", line 6, in
__new__
cls._instance = super().__new__(cls, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: object.__new__() takes exactly one argument (the type to
instantiate)
I am quite puzzled as it looks as if this code will not work if the
super-class is 'object'. Any suggestions on how to proceed?
Don't pass kwargs to object.__new__ because it doesn't expect it.
Incidentally, kwargs will never be None, and there's no point in giving
a return type for __init__ because it can only ever return None.
--
https://mail.python.org/mailman/listinfo/python-list