类型(名称,基数,字典)可用于创建实例(类的对象),例如在Singleton

时间:2017-11-09 07:35:05

标签: python python-3.x metaclass

因此可以使用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)

1 个答案:

答案 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())