想继承一个类时,有报错:
from functools import wraps
def singleton(cls):
instance = None
@wraps(cls)
def wrap(*args, **kwargs):
nonlocal instance
if not instance:
instance = cls(*args, **kwargs)
return instance
return wrap
@singleton
class Config:
def __init__(self):
pass
class AnimalConfig(Config):
def __init__(self):
super(AnimalConfig, self).__init__()
Traceback (most recent call last):
File "D:\Python\Python36\Lib\site-packages\IPython\core\interactiveshell.py", line 3343, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-8-1c3f343d6e87>", line 1, in <module>
class AnimalConfig(Config):
TypeError: function() argument 1 must be code, not str
此时的基类Config 已经不是一个类了,是一个函数。 type(Config) 可以看到结果是function。
经过了上面装饰器的修改,已经变成function了,自然不能继承function
一种可行的解决方法是:
ClassConfig = Config().__class__
class AnimalConfig(ClassConfig):
def __init__(self):
super(AnimalConfig, self).__init__()