__init__
클래스를 초기화하는 동안 클래스 메서드에서 호출하는 것을 피할 수있는 방법이 있습니까?Python : 초기화 프로그램을 호출하지 않고 클래스 인스턴스 생성
효과적인 비교를 위해 파이썬에서 대소 문자를 구별하지 않는 문자열 클래스를 만들고 싶지만 __init__
을 호출하지 않고 새 인스턴스를 만드는 데 문제가 있습니다.
>>> class String:
def __init__(self, string):
self.__string = tuple(string.split())
self.__simple = tuple(self.__simple())
def __simple(self):
letter = lambda s: ''.join(filter(lambda s: 'a' <= s <= 'z', s))
return filter(bool, map(letter, map(str.lower, self.__string)))
def __eq__(self, other):
assert isinstance(other, String)
return self.__simple == other.__simple
def __getitem__(self, key):
assert isinstance(key, slice)
string = String()
string.__string = self.__string[key]
string.__simple = self.__simple[key]
return string
def __iter__(self):
return iter(self.__string)
>>> String('Hello, world!')[1:]
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
String('Hello, world!')[1:]
File "<pyshell#1>", line 17, in __getitem__
string = String()
TypeError: __init__() takes exactly 2 positional arguments (1 given)
>>>
나는 슬라이스로 새 개체를 초기화하는 데 사용할
string = String(); string.__string = self.__string[key]; string.__simple = self.__simple[key]
를 교체해야합니까
?
은 편집 :로 아래 서면 답변을 영감으로
, 이니셜 신속 인수를 확인하기 위해 편집되었다.
def __init__(self, string=None):
if string is None:
self.__string = self.__simple =()
else:
self.__string = tuple(string.split())
self.__simple = tuple(self.__simple())
가능한 복제본 [\ _ \ _ init \ _ \ _을 (를) 호출하지 않고 클래스를 인스턴스화하는 방법이 있습니까?] (http : // stackoverflow.com/questions/6383914/is-there-a-way-to-instantiate-a-class-without-calling-init) – kay