想继承一个类时,有报错:
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__()
在Python中尝试使用装饰器实现单例模式时遇到了错误,导致基类Config被转换为函数,无法进行继承。错误信息显示函数参数必须为code对象而非字符串。为解决此问题,可以将Config实例的类类型赋值给AnimalConfig的基类,从而避免直接继承被装饰后的函数。具体做法是通过Config().__class__获取Config的类类型来创建AnimalConfig。
1418

被折叠的 条评论
为什么被折叠?



