나는 모든 유형/클래스를 팩토리 메소드로 대체하고 클래스 객체의 대부분의 기능을 유지할 수있는 프록시 클래스를 고안했습니다. 완전히 원래의 클래스 객체를 대체하고 여전히 다음과 같은 것들을 할 수 있기 때문에 내가 팩토리 메소드의 구현을 좋아python에서 repr()과 같은 함수를 내 프록시 클래스와 함께 사용하려면 어떻게해야합니까?
class ProxyClass:
def __init__(self, cls):
self._ProxyClass_cls = cls
def __getattr__(self, name):
return getattr(self._ProxyClass_cls, name)
class _strProxy(ProxyClass):
def __call__(self, s):
if '\n' in s:
raise ValueError
if s not in self._cache:
self._cache[s] = self._ProxyClass_cls(s)
return self._cache[s]
str = _strProxy(str)
str._cache = {}
>>> s = str('hello')
>>> s
'hello'
>>> type(s)
<type 'str'>
>>> str('hello\n')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in __call__
ValueError
:
>>> map(str.split, [str('foo bar'), str('bar foo')])
[['foo', 'bar'], ['bar', 'foo']]
유일한 문제 I를 여기 그것이 작동하는 방법의 예입니다 이 예에서
>>> repr(str)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: descriptor '__repr__' of 'str' object needs an argument
이
repr()
0을 호출하려고 : 발견 자체는
repr()
같은 클래스의 작업을 함께
type.__repr__(str)
대신입니다. 나는
str.__class__
을 변경 수정 시도했지만 문제는이 경우에 불가능하다는 것을 발견 :
는
>>> str.__class__ = type
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __class__ must be set to a class
는
사람은 repr(str)
의 기능이나 내가 뭐하는 거지 달성하기 어쩌면 다른 방법을 복원 할 수있는 방법을 알고 있나요?
class ProxyClass(object):
당신이 필요가 없습니다, 모든 클래스는, 어쨌든 object
에서 상속 :
텍스트 파일에 복사/붙여 넣기를 수행 할 수있는 실제 작업 코드를 게시하는 것이 가장 좋습니다. 위의 내용은 편집해야하는'>>>'와'...'가 있으며, 위의 내용은 추가 내용을 편집 한 후에도 올바르게 작동하지 않는 오타가 있습니다. – steveha
@steveha 좋아, 편집 할게. 오타가 무엇입니까? – Matt
오타를 수정했습니다. '_strProxy()'클래스는'_strPproxy()'를 사용했습니다. (호출은'_strProxy()') – steveha