有没有办法避免在初始化类时调用 __ init __ ,例如从类方法调用
Is there any way to avoid calling __init__ on a class while initializing it, such as from a class method?
我试图在Python中创建一个case和标点符号不敏感的字符串类用于有效的比较目的,但是无法创建一个新的实例,而不调用 __ init __ 。
I am trying to create a case and punctuation insensitive string class in Python used for efficient comparison purposes but am having trouble creating a new instance without calling __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] 使用切片初始化新对象?
What should I replace string = String(); string.__string = self.__string[key]; string.__simple = self.__simple[key] with to initialize the new object with the slices?
EDIT:
由于下面的答案的启发,初始化程序已经被编辑以快速检查没有参数。
As inspired by the answer written below, the initializer has been edited to quickly check for no arguments.
def __init__(self, string=None): if string is None: self.__string = self.__simple = () else: self.__string = tuple(string.split()) self.__simple = tuple(self.__simple())推荐答案
在这个例子中使用元类提供了一个很好的解决方案。元类有限的使用,但工作正常。
Using a metaclass provides a nice solution in this example. The metaclass has limited use but works fine.
>>> class MetaInit(type): def __call__(cls, *args, **kwargs): if args or kwargs: return super().__call__(*args, **kwargs) return cls.__new__(cls) >>> class String(metaclass=MetaInit): 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:] <__main__.String object at 0x02E78830> >>> _._String__string, _._String__simple (('world!',), ('world',)) >>>更多推荐
Python:创建类实例而不调用initializer
发布评论