2017-12-31 36 views
2

간단히 "012"를 구현하는 데 사용되는 을 정의하는 기본 클래스로 구현 된이 간단한 프로그램이 있습니다. 그러나 나는 더 이상 초기화에 방법을 인수를 보낼 수 - 나는 내가 어떻게해야합니까 때파이썬 덮어 쓰기 __new__은 __init__에 인수를 보낼 수 없습니다.

class Singleton(object): 
    _instances = {} 

    def __new__(cls, *args, **kwargs): 
     print(args, kwargs) 
     if cls._instances.get(cls, None) is None: 
      cls._instances[cls] = super(Singleton, cls).__new__(cls, *args, **kwargs) 
     return Singleton._instances[cls] 


class OneOfAKind(Singleton): 

    def __init__(self): 
     print('--> OneOfAKind __init__') 
     Singleton.__init__(self) 


class OneOfAKind2(Singleton): 

    def __init__(self, onearg): 
     print('--> OneOfAKind2 __init__') 
     Singleton.__init__(self) 
     self._onearg = onearg 


x = OneOfAKind() 
y = OneOfAKind() 
print(x == y) 
X = OneOfAKind2('testing') 

출력은 다음과 같습니다 : 싱글에서 새로운 슈퍼 전화를 "형식 오류) 객체 (매개 변수를 사용하지 않는"

() {} 
Traceback (most recent call last): 
    File "./mytest.py", line 29, in <module> 
    x = OneOfAKind() 
    File "./mytest.py", line 10, in __new__ 
    cls._instances[cls] = super(Singleton, cls).__new__(cls,(), {}) 
TypeError: object() takes no parameters 
+0

을 파이썬 3을 사용하고 있습니까? – BorrajaX

답변

0

오른쪽, 당신이 상속되고 super에서 호출하면 어떤 인수하지 않는 것입니다 object 이유는

In [54]: object('foo', 'bar') 
--------------------------------------------------------------------------- 
TypeError         Traceback (most recent call last) 
<ipython-input-54-f03d0963548d> in <module>() 
----> 1 object('foo', 'bar') 

TypeError: object() takes no parameters 

이 같은 작업을 수행하려는 경우, 내가 대신 서브 클래스의 metaclass를 추천하고, 대신 객체 생성에 대한 __new__metaclass 무시 __call__ 재정의 : 다음

import six ## used for compatibility between py2 and py3 

class Singleton(type): 
    _instances = {} 

    def __call__(cls, *args, **kwargs): 
     if Singleton._instances.get(cls, None) is None: 
      Singleton._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) 
     return Singleton._instances[cls] 

@six.add_metaclass(Singleton) 
class OneOfAKind(object): 

    def __init__(self): 
     print('--> OneOfAKind __init__') 

@six.add_metaclass(Singleton) 
class OneOfAKind2(object): 

    def __init__(self, onearg): 
     print('--> OneOfAKind2 __init__') 
     self._onearg = onearg 

: 내가 상상

In [64]: OneOfAKind() == OneOfAKind() 
--> OneOfAKind __init__ 
Out[64]: True 

In [65]: OneOfAKind() == OneOfAKind() 
Out[65]: True 

In [66]: OneOfAKind() == OneOfAKind2('foo') 
Out[66]: False 
+0

굉장! 감사! –