如何在不调用初始化程序的情况下创建类实例? [英] How to create a class instance without calling initializer?

查看:77
本文介绍了如何在不调用初始化程序的情况下创建类实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以避免在初始化类时在类上调用 __ init __

Is there any way to avoid calling __init__ on a class while initializing it, such as from a class method?

我试图在Python中创建一个不区分大小写和标点符号的字符串类,以进行有效的比较,但是在不调用 __ 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?

编辑:

受到以下答案的启发,已对初始化程序进行了编辑,以快速检查是否没有参数。

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',))
>>> 

附录:

六年后,我的观点更倾向于 Alex Martelli的答案,而不是我自己的方法。考虑到元类,下面的答案显示了使用和不使用元类都可以解决问题的方法:

After six years, my opinion favors Alex Martelli's answer more than my own approach. With meta-classes still on the mind, the following answer shows how the problem can be solved both with and without them:

#! /usr/bin/env python3
METHOD = 'metaclass'


class NoInitMeta(type):
    def new(cls):
        return cls.__new__(cls)


class String(metaclass=NoInitMeta if METHOD == 'metaclass' else type):
    def __init__(self, value):
        self.__value = tuple(value.split())
        self.__alpha = tuple(filter(None, (
            ''.join(c for c in word.casefold() if 'a' <= c <= 'z') for word in
            self.__value)))

    def __str__(self):
        return ' '.join(self.__value)

    def __eq__(self, other):
        if not isinstance(other, type(self)):
            return NotImplemented
        return self.__alpha == other.__alpha

    if METHOD == 'metaclass':
        def __getitem__(self, key):
            if not isinstance(key, slice):
                raise NotImplementedError
            instance = type(self).new()
            instance.__value = self.__value[key]
            instance.__alpha = self.__alpha[key]
            return instance
    elif METHOD == 'classmethod':
        def __getitem__(self, key):
            if not isinstance(key, slice):
                raise NotImplementedError
            instance = self.new()
            instance.__value = self.__value[key]
            instance.__alpha = self.__alpha[key]
            return instance

        @classmethod
        def new(cls):
            return cls.__new__(cls)
    elif METHOD == 'inline':
        def __getitem__(self, key):
            if not isinstance(key, slice):
                raise NotImplementedError
            cls = type(self)
            instance = cls.__new__(cls)
            instance.__value = self.__value[key]
            instance.__alpha = self.__alpha[key]
            return instance
    else:
        raise ValueError('METHOD did not have an appropriate value')

    def __iter__(self):
        return iter(self.__value)


def main():
    x = String('Hello, world!')
    y = x[1:]
    print(y)


if __name__ == '__main__':
    main()

这篇关于如何在不调用初始化程序的情况下创建类实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆