因此可以使用object.__new__(cls)
和super().__new__(cls)
函数来创建实例,但是我可以使用type(name, bases, dict)(*args, **kwargs)
来创建实例吗?
class Singleton(object):
instance = None
def __init__(self, *args, **kwargs):
pass
def __new__(cls, *args, **kwargs):
if isinstance(cls.instance, type(None)):
mcls = cls.__class__
cls.instance = type(mcls.__name__, mcls.__bases__, dict(cls.__dict__))(*args, *kwargs)
return cls.instance
s = Singleton()
print(s)
答案 0 :(得分:0)
所以我找不到在__new__
中保留cls.__dict__
方法的方法,这会导致重复,所以我在创建课程之前将其删除。
class FooMixin(object):
def print_somth(self):
print('smth....')
class Singleton(FooMixin):
instance = None
def __new__(cls, *args, **kwargs):
if cls.instance is None:
temp = dict(cls.__dict__)
del temp['__new__']
temp['test'] = 100
cls.instance = type('Singleton', cls.__bases__, temp)(*args, **kwargs)
return cls.instance
s = Singleton()
print(s.test, s.print_somth())