首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在不调用初始化器的情况下创建一个类实例?

如何在不调用初始化器的情况下创建一个类实例?
EN

Stack Overflow用户
提问于 2010-01-31 02:41:37
回答 4查看 36.6K关注 0票数 37

有没有办法避免在初始化类时调用__init__,比如从类方法中调用?

我试图用Python语言创建一个不区分大小写和标点符号的字符串类,用于有效的比较,但在不调用__init__的情况下创建一个新实例时遇到了问题。

代码语言:javascript
复制
>>> 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],才能用切片初始化新对象?

编辑:

由于受到以下答案的启发,初始化器已被编辑为快速检查无参数。

代码语言:javascript
复制
def __init__(self, string=None):
    if string is None:
        self.__string = self.__simple = ()
    else:
        self.__string = tuple(string.split())
        self.__simple = tuple(self.__simple())
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2013-02-07 04:30:18

在这个例子中,使用元类提供了一个很好的解决方案。元类的用法有限,但运行良好。

代码语言:javascript
复制
>>> 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's answer而不是我自己的方法。考虑到元类仍然在脑海中,下面的答案显示了如何在有元类和没有元类的情况下解决问题:

代码语言:javascript
复制
#! /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()
票数 2
EN

Stack Overflow用户

发布于 2010-01-31 03:46:52

如果可行,让__init__被调用(并通过适当的参数使调用无伤大雅)是更可取的。然而,如果需要太多改动,您确实有另一种选择,只要您避免使用旧式类的灾难性选择(在新代码中使用旧式类没有很好的理由,以及 to的几个很好的理由):

代码语言:javascript
复制
   class String(object):
      ...

   bare_s = String.__new__(String)

这个习惯用法通常用在classmethod中,它的作用是作为“替代构造函数”,所以你通常会看到它以这样的方式使用:

代码语言:javascript
复制
@classmethod 
def makeit(cls):
    self = cls.__new__(cls)
    # etc etc, then
    return self

(这样,类方法将被正确地继承,并在子类而不是基类上调用时生成子类实例)。

票数 52
EN

Stack Overflow用户

发布于 2013-02-06 08:22:17

标准的pickle和copy模块使用的一个技巧是创建一个空类,使用它实例化对象,然后将该实例的__class__分配给“真正的”类。例如:

代码语言:javascript
复制
>>> 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

但请注意,这种方法很少是必要的。绕过__init__可能会产生一些意想不到的副作用,特别是在您不熟悉原始类的情况下,因此请确保您知道自己在做什么。

票数 12
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2168964

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档