Using __new__
Jonathan Gossage
jgossage at gmail.com
Sat Feb 17 17:35:21 EST 2024
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 at 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?
--
Jonathan Gossage
More information about the Python-list
mailing list