Python3.6单例模式报错TypeError: object() takes no parameters的解决方法
2017-11-11 21:19
351 查看
前日学习python实现单例模式,我安装环境是python3.6.2,代码如下:
测试类如下:
TypeError: object() takes no parameters
我首先百度了,好多回答都是以下两种原因:
1、 init方法左右的下划线只写了一个
2、 init方法写成int了。
我仔细检查了自己的方法,发现还是都没有这两种错误;最后我又单独安装python2.7,结果运行出了结果:
[name:albert1] [id:58899704]
[name:albert2] [id:58899704]
那么在python3.6中应该如何修改呢,代码应该修改如下(注意红色地方):
# python3.6.2
class Singleton(object):
_inst = None
def __new__(cls, *args, **kwargs):
if not cls._inst :
cls._inst = super(Singleton, cls).__new__(cls)
return cls._inst
已经验证对于结果没有影响,所以大家以后在用的时候要注意
class Singleton(object): _inst = None def __new__(cls, *args, **kwargs): if not cls._inst : cls._inst = super(Singleton, cls).__new__(cls, *args, **kwargs) return cls._inst
测试类如下:
class Test(Singleton): def __init__(self, name): self.name = name def output(self): print('[name:%s] [id:%s]' % (self.name, id(self))) if __name__ == '__main__': t1 = Test('albert1') t1.output() t2 = Test('albert2') t2.output()我一运行没想到结果报错:
TypeError: object() takes no parameters
我首先百度了,好多回答都是以下两种原因:
1、 init方法左右的下划线只写了一个
2、 init方法写成int了。
我仔细检查了自己的方法,发现还是都没有这两种错误;最后我又单独安装python2.7,结果运行出了结果:
[name:albert1] [id:58899704]
[name:albert2] [id:58899704]
那么在python3.6中应该如何修改呢,代码应该修改如下(注意红色地方):
# python3.6.2
class Singleton(object):
_inst = None
def __new__(cls, *args, **kwargs):
if not cls._inst :
cls._inst = super(Singleton, cls).__new__(cls)
return cls._inst
已经验证对于结果没有影响,所以大家以后在用的时候要注意
相关文章推荐
- 在Python中TypeError: object() takes no parameters新手问题的解决办法
- 解决python入门object() takes no parameters
- __new__方法以及TypeError: object() takes no parameters的处理
- TypeError: object() takes no parameters
- AttributeError: 'module' object has no attribute 'Frame' 解决方法
- Django报错:AttributeError: 'module' object has no attribute 的解决方法
- Python脚本报错AttributeError: ‘module’ object has no attribute’xxx’解决方法
- Python_TypeError:object() takes no parameters
- error while loading shared libraries: libnet.so.9: cannot open shared object file: No such **解决方法
- 解决方法——AttributeError: 'module' object has no attribute 'VideoWriter_fourcc'
- RAC srvctl 命令报 libpthread.so.0 cannot open shared object file No such file or directory 解决方法
- 使用Anaconda与pip报错'_NamespacePath' object has no attribute 'sort'的解决方法
- 关于python里运行出现'module' object has no attribute 'xxxx'等问题解决方法
- django view.py error 'QuerySet' object has no attribute 'save' 解决方法
- python object() takes no parameters
- Keras深度学习框架学习笔记(3) - AttributeError:’module’ object has no attribute ‘ifelse’错误信息的解决方法
- Python脚本报错AttributeError: ‘module’ object has no attribute’xxx’解决方法
- Python3问题TypeError: object() takes no parameters
- Python脚本报错AttributeError: ‘module’ object has no attribute’xxx’解决方法
- python:TypeError: this constructor takes no arguments解决方法