如何在不调用初始化方法的情况下创建类实例?
有没有办法在初始化一个类的时候不调用 __init__
方法,比如通过类方法来实现?
我正在尝试创建一个不区分大小写和标点符号的字符串类,用于高效比较,但在没有调用 __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())
4 个回答
标准的pickle和copy模块使用的一个技巧是先创建一个空的类,然后用这个空类来实例化对象,最后再把这个实例的__class__
属性指向“真实”的类。例如:
>>> 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__
方法可能会带来一些意想不到的副作用,特别是如果你对原来的类不太了解,所以一定要确保你知道自己在做什么。
在可能的情况下,让 __init__
被调用是比较好的做法(而且可以通过合适的参数让这个调用变得简单)。不过,如果这样做太复杂,你还有其他选择,只要你避免使用旧式类(在新代码中没有好的理由使用旧式类,而且有很多不使用它的好理由)……:
class String(object):
...
bare_s = String.__new__(String)
这种写法通常用在 classmethod
中,这些方法被设计成“替代构造函数”,所以你通常会看到它以这样的方式使用……:
@classmethod
def makeit(cls):
self = cls.__new__(cls)
# etc etc, then
return self
(这样,当在子类上调用时,类方法会正确地被继承,并生成子类的实例,而不是基类的实例)。
使用元类在这个例子中提供了一个不错的解决方案。虽然元类的用处有限,但在这里效果很好。
>>> 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的回答,而不是我自己的方法。考虑到元类,下面的回答展示了如何在有和没有元类的情况下解决这个问题:
#! /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()