内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用
我试图在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())
>>> class MyClass(object): ... init = False ... def __init__(self): ... print 'init called!' ... self.init = True ... def hello(self): ... print 'hello world!' ... >>> class Empty(object): ... pass ... >>> a = MyClass() init called! >>> a.hello() hello world! >>> print a.init True >>> b = Empty() >>> b.__class__ = MyClass >>> b.hello() hello world! >>> print b.init False