Python:创建类实例而不调用initializer

编程入门 行业动态 更新时间:2024-10-24 04:31:55
本文介绍了Python:创建类实例而不调用initializer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

有没有办法避免在初始化类时调用 __ 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

本文发布于:2023-10-28 19:17:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1537540.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:而不   实例   Python   initializer

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!